Python日期时间相减而忽略周末

2022-05-21 08:36:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我熟悉Python中从当前日期减去天数的timedelta方法(见下文);不过,我很好奇我怎么能让它自动跳过周末

from datetime import datetime, timedelta
target_date = datetime.today() - timedelta(days=dayoffset)

例如,2019-10-08减去3天就是2019-10-03(因为第5天和第6天是周末)。谢谢你


Tags: 方法fromimporttargettodaydatetimedatedaystimedelta见下文天数dayoffset
1条回答
网友
1楼 ·

您可以尝试datetime.weekday(),它将日期返回到0-6之间的值,而5和6是周末

Read more on this.

from datetime import datetime, timedelta
def diff_day(start, end):
    delta = timedelta(days=1)
    d = start
    diff = 0
    weekend = [5, 6]
    while d < end:
        if d.weekday() not in weekend:
            diff += 1
        d += delta
    return diff
>>>start = datetime(2019,10,3)
>>>end = datetime(2019,10,8)
>>>diff_day(start, end)
3