You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python根据各国假日日历获取指定日期的下一个工作日?

Python 获取不同国家/地区的下一个工作日

要实现根据指定国家/地区的假日规则获取下一个工作日,可以借助holidays库——它内置了全球多数国家和地区的官方假日数据,结合日期的星期判断就能轻松解决问题。

步骤1:安装依赖库

执行以下命令安装holidays:

pip install holidays

步骤2:编写核心函数

这个函数会从目标日期开始,逐个往后检查,直到找到第一个既不是周末(默认周一至周五为工作日)也不属于对应国家假日的日期:

import datetime
import holidays

def get_next_workday(target_date, country_code):
    # 初始化对应国家/地区的假日集合
    country_holiday_set = holidays.CountryHoliday(country_code)
    current_check_date = target_date
    
    while True:
        # 判断是否为工作日:非周末(周一到周五)且不在假日列表中
        if current_check_date.weekday() < 5 and current_check_date not in country_holiday_set:
            return current_check_date
        # 非工作日则往后推一天
        current_check_date += datetime.timedelta(days=1)

步骤3:测试示例场景

针对你给出的2023年1月23日的例子,运行以下代码验证:

# 目标测试日期
test_date = datetime.date(2023, 1, 23)

# 中国香港(ISO代码:HK)
hk_workday = get_next_workday(test_date, 'HK')
print(f"中国香港的下一个工作日:{hk_workday.strftime('%Y年%m月%d日')}")

# 印度(ISO代码:IN)
in_workday = get_next_workday(test_date, 'IN')
print(f"印度的下一个工作日:{in_workday.strftime('%Y年%m月%d日')}")

# 新加坡(ISO代码:SG)
sg_workday = get_next_workday(test_date, 'SG')
print(f"新加坡的下一个工作日:{sg_workday.strftime('%Y年%m月%d日')}")

运行结果会和你给出的示例一致:

  • 中国香港返回2023年1月26日
  • 印度返回2023年1月23日
  • 新加坡返回2023年1月25日

补充说明

  • holidays库的国家/地区代码遵循ISO 3166标准,如需其他地区的支持,可以查阅库的官方文档获取对应代码。
  • 部分国家/地区的周末并非周六周日(如中东国家多为周五、周六),此时需要修改函数中判断周末的逻辑,例如沙特阿拉伯(代码SA)可将判断条件改为current_check_date.weekday() not in [4, 5](周五为weekday=4,周六为weekday=5)。

内容的提问来源于stack exchange,提问作者user1769197

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:35:20