2017-07-06 144 views
0

我試圖在營業日曆中添加日期。不知何故,我應該收到日期28.04.2015,但使用我的代碼我得到2015年4月24日。我正在使用假期日曆,僅在週一至週五(星期一至星期五)。代碼如下所示:在Python中添加營業日日曆

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) 
+0

你可以發表你的完整的代碼? – Veltro

+0

@Veltro,謝謝。只是做了 – MCM

+0

簡單的測試用例,你的代碼不工作:今天是星期四,明天是假期。在這種情況下,getNextBsinessDay()將在下個工作日的星期天返回。 –

回答

1

這裏是最後的工作液

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))