在Python中向工作日日历添加天数

2024-09-19 23:32:48 发布

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

我正在尝试将天数添加到工作日日历中。不知何故,我应该收到日期28.04.2015,但使用我的代码,我得到了24.04.2015。我使用假日日历,只有工作日(星期一到星期五)。代码如下所示:

from datetime import datetime, timedelta, date    
import holidays

def getNextBusinessDays(date, num):
    for i in range(0, num):
        date = getNextBusinessDay(date)
    return date    

def getNextBusinessDay(fromDate):

    Holiday = holidays.DE()

    nextBuinessDate = datetime.strptime(fromDate, "%Y-%m-%d")
    nextBuinessDate = nextBuinessDate + timedelta(days=1) 
    if date.weekday(nextBuinessDate) not in range(0, 5) and nextBuinessDate not in Holiday:
        nextBuinessDate = nextBuinessDate + timedelta(days=1)
    if date.weekday(nextBuinessDate) not in range(0, 5) and nextBuinessDate not in Holiday:
        nextBuinessDate = nextBuinessDate + timedelta(days=1)
    return nextBuinessDate.strftime('%Y-%m-%d')

if __name__ == '__main__':

    dateshift = getNextBusinessDays('2015-02-01', 60)
    print(dateshift)

Tags: 代码inimportdatetimedateifdefholidays
1条回答
网友
1楼 · 发布于 2024-09-19 23:32:48

这是最终的解决方案

import datetime as dt
import holidays

Holiday = holidays.DE()

def getNextBusinessDay(date, n):
    for i in range(n):
        nextday = date1 + dt.timedelta(days=1)
        while nextday.weekday() > 4 or nextday in Holiday:
            nextday += dt.timedelta(days=1)
        date = nextday
    return date

#test
datetest = dt.datetime.strptime('02-04-15', '%d-%m-%y')
print(getNextBusinessDay(datetest,1))

相关问题 更多 >