Add n business days to a given date ignoring holidays and weekends in python

前端 未结 11 647
天涯浪人
天涯浪人 2020-12-05 10:32

I\'m trying to add n (integer) working days to a given date, the date addition has to avoid the holidays and weekends (it\'s not included in the working days)

11条回答
  •  长情又很酷
    2020-12-05 11:06

    There is no real shortcut to do this. Try this approach:

    1. Create a class which has a method skip(self, d) which returns True for dates that should be skipped.
    2. Create a dictionary in the class which contains all holidays as date objects. Don't use datetime or similar because the fractions of a day will kill you.
    3. Return True for any date that is in the dictionary or d.weekday() >= 5

    To add N days, use this method:

    def advance(d, days):
        delta = datetime.timedelta(1)
    
        for x in range(days):
            d = d + delta
            while holidayHelper.skip(d):
                d = d + delta
    
        return d
    

提交回复
热议问题