Pyth0nicPenguin
Pyth0nicPenguin

Reputation: 148

Adding 6 business days

I have a function that will calculate 6 days, it works, and it's wonderful and all, but I need a way to skip Saturday and Sunday. How can I fix this function in order to have it skip Saturday and Sunday?

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)

Upvotes: 0

Views: 221

Answers (2)

nehem
nehem

Reputation: 13642

You can use this code that I use. The attempt it is add not just 6 days, but any number of days.

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

For example getNextBusinessDays('2016-10-20', 6) will produce "2016-10-28"

Upvotes: 1

Psytho
Psytho

Reputation: 3384

As shifting for 6 days always includes shifting over a weekend, you can shift for 8 days (6 days + Saturday and Sunday):

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

Upvotes: 1

Related Questions