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

Python实现排除周末的日期减5个工作日逻辑(输入格式YYYYMMDD)

Python实现往前推指定工作日的日期计算

核心思路

  1. 将输入的YYYYMMDD格式字符串转换为datetime对象,方便日期运算
  2. 从目标日期开始逐天往前遍历,跳过周六(weekday=5)和周日(weekday=6)
  3. 每找到一个有效工作日就计数,直到累计够5个工作日,返回该日期的YYYYMMDD格式字符串

代码实现

from datetime import datetime, timedelta

def get_prev_five_workdays(input_date_str):
    # 转换输入字符串为datetime对象
    target_date = datetime.strptime(input_date_str, "%Y%m%d")
    count = 0
    current_date = target_date
    
    while count < 5:
        # 往前推一天
        current_date -= timedelta(days=1)
        # 判断是否为工作日(周一到周五对应weekday() 0-4)
        if current_date.weekday() < 5:
            count += 1
    
    # 转换回YYYYMMDD格式字符串返回
    return current_date.strftime("%Y%m%d")

验证示例

# 测试题目中的例子
print(get_prev_five_workdays("20230228"))  # 输出: 20230221

扩展说明

  • 如果需要调整往前推的工作日数量,只需修改循环中的count < 5为目标数字即可
  • 该方法逻辑简单直观,对于少量工作日计算(比如几十天内)效率足够;如果是超大天数计算,可以优化为按周批量计算(每周跳过2天),减少循环次数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:38:09