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

考虑节假日的业务日期选择:如何设置符合要求的起止工作日

现有代码仅处理了周末校验逻辑,存在导入模块命名冲突、未对接手动维护的节假日列表、未兼容节假日和周末连续出现场景的问题,优化实现如下:

步骤1:规范holiday.csv格式

csv文件仅需1列存储YYYY-MM-DD格式的节假日日期即可,示例内容:

holiday_date
2024-01-01
2024-02-10
2024-02-12
2024-05-01

步骤2:完整实现代码

import pandas as pd
from datetime import datetime, timedelta

# 读取节假日列表并转为date类型的集合,查询效率更高
holiday_df = pd.read_csv('holiday.csv')
holiday_set = set(pd.to_datetime(holiday_df['holiday_date']).dt.date)

def is_workday(check_date) -> bool:
    """校验传入日期是否为工作日:非周末 + 非自定义节假日"""
    # weekday返回值规则:0=周一,5=周六,6=周日
    if check_date.weekday() >= 5:
        return False
    if check_date in holiday_set:
        return False
    return True

# 计算结束日期:从昨天(t-1)开始往前找最近的工作日
end_date = (datetime.today() - timedelta(days=1)).date()
while not is_workday(end_date):
    end_date -= timedelta(days=1)

# 计算开始日期:从结束日期前一天开始往前找最近的工作日
begin_date = end_date - timedelta(days=1)
while not is_workday(begin_date):
    begin_date -= timedelta(days=1)

# 结果验证
print(f"开始日期:{begin_date.strftime('%Y-%m-%d')}")
print(f"结束日期:{end_date.strftime('%Y-%m-%d')}")

逻辑说明

  • 封装独立的工作日校验函数,避免重复编写判断逻辑,后续节假日规则调整也更易维护
  • 用循环向前查找的逻辑替代固定减1/2天的硬编码,兼容连续多日非工作日(比如节假日和周末连休)的场景
  • 把节假日转成set存储,查询时间复杂度为O(1),即使节假日列表很长也不会影响运行效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:36:01