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

前端 未结 11 644
天涯浪人
天涯浪人 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:14

    I wanted a solution that wasn't O(N) and it looked like a fun bit of code golf. Here's what I banged out in case anyone's interested. Works for positive and negative numbers. Let me know if I missed anything.

    def add_business_days(d, business_days_to_add):
        num_whole_weeks  = business_days_to_add / 5
        extra_days       = num_whole_weeks * 2
    
        first_weekday    = d.weekday()
        remainder_days   = business_days_to_add % 5
    
        natural_day      = first_weekday + remainder_days
        if natural_day > 4:
            if first_weekday == 5:
                extra_days += 1
            elif first_weekday != 6:
                extra_days += 2
    
        return d + timedelta(business_days_to_add + extra_days)
    

提交回复
热议问题