小编典典

在给定日期后找到第一个星期一的日期

python

给定一个特定的日期(例如2011-07-02),我如何找到该日期之后的下一个星期一(或该日的任何工作日)的日期?


阅读 170

收藏
2020-12-20

共1个答案

小编典典

import datetime
def next_weekday(d, weekday):
    days_ahead = weekday - d.weekday()
    if days_ahead <= 0: # Target day already happened this week
        days_ahead += 7
    return d + datetime.timedelta(days_ahead)

d = datetime.date(2011, 7, 2)
next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday...
print(next_monday)
2020-12-20