添加6个工作日

时间:2016-10-25 12:58:54

标签: python-2.7 datetime

我有一个计算6天的功能,它有效,而且很棒,但是我需要一种方法来跳过周六和周日。如何修复此功能以使其在周六和周日跳过?

def calc_bus_day(start_day):
    if start_day.isoweekday() in range(1, 5):
        shift = 6
        returnDate = start_day + datetime.timedelta(days=shift)
        if returnDate.isoweekday() == 0:
            return "{:%m-%d-Y}".format(returnDate + datetime.timedelta(days=1))
        elif returnDate.isoweekday() == 5:
            return "{:%m-%d-%Y}".format(returnDate + datetime.timedelta(days=2))
        else:
            return "{:%m-%d-%Y}".format(returnDate)

2 个答案:

答案 0 :(得分:1)

由于轮换6天总是包括轮换周末,你可以换班8天(6天+周六和周日):

def calc_bus_day(start_day):
    if start_day.isoweekday() in range(1, 5):
        shift = 8
        < your code >

答案 1 :(得分:1)

您可以使用我使用的此代码。它的尝试不仅仅是6天,而是任意天数。

from datetime import datetime, timedelta, date    

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

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

例如getNextBusinessDays('2016-10-20', 6)将生成&#34; 2016-10-28&#34;