如何在Python中计算排除周末的X个工作日之前的日期
解决工作日日期计算问题
问题描述
若当前日期为8/22,计算往前推6个工作日的日期,预期结果为8/12(仅统计工作日)。尝试使用weekday()函数判断周六(返回值5)、周日(返回值6)并跳过,但未成功。现有代码如下:
from datetime import datetime, timedelta age = 6 counter = 0 difference = datetime.today() - timedelta(counter) while counter <= age: difference = datetime.today() - timedelta(counter) counter = counter + 1
该代码未排除周末,需要解决此问题。
修正后的代码
核心逻辑是:每往前推一天,先判断是否为周末,若是则跳过不计入工作日计数;若是工作日则增加计数,直到达到目标工作日数量。
from datetime import datetime, timedelta target_workdays = 6 current_date = datetime.today() counter = 0 while counter < target_workdays: current_date -= timedelta(days=1) # 周一到周五的weekday()返回值为0-4,属于工作日 if current_date.weekday() < 5: counter += 1 print(f"往前推{target_workdays}个工作日的日期是:{current_date.strftime('%m/%d')}")
代码说明
- 初始化
current_date为当前日期,counter用于统计已找到的工作日数量 - 循环内每天往前推移一天:
- 若当天是工作日,
counter加1 - 若为周末,则不改变计数,继续往前推
- 若当天是工作日,
- 当
counter等于目标工作日数时,循环停止,此时的current_date即为结果
测试当前日期为8/22时,运行代码会得到预期结果8/12。
内容的提问来源于stack exchange,提问作者Jonathan Vega
相关产品推荐
相关产品推荐

