Home > Mobile >  Python - Add OR Subtract N *Business* Days from Date Input
Python - Add OR Subtract N *Business* Days from Date Input

Time:03-29

I am trying to make a function that will add or subtract business days to a date. I have a form that contains the following:

  • Input: DatePicker (datetime)
  • Input: NumberOfDays (int)
  • Button: CalendarDays/BusinessDays
  • Output: FinalDate from calculation

HURDLE: I can ONLY use datetime and timedelta - no numpy, pandas, etc. The code below works, however, it only works for adding business days.

GOAL: If possible, I would like to use a single function that will calculate business days, and use a positive or negative integer to determine if the business day calculation is addition or subtraction. The code below works, however, it only works with a positive integer input, and only adds business days.

Any help is greatly appreciated. Thank you.

from datetime import datetime, timedelta

def bizday_calc_func(self, start_date, num_days):
    my_start_date = start_date
    my_num_days = num_days
    while my_num_days > 0:
      my_start_date  = timedelta(days=1)
      weekday = my_start_date.weekday()
      if weekday >= 5:
        continue
      my_num_days -= 1
    return my_start_date

CodePudding user response:

Seems like a small tweak to your routine would do the trick:

from datetime import datetime, timedelta

def bizday_calc_func(self, start_date, num_days):
    my_start_date = start_date
    my_num_days = abs(num_days)
    inc = 1 if num_days > 0 else -1
    while my_num_days > 0:
      my_start_date  = timedelta(days=inc)
      weekday = my_start_date.weekday()
      if weekday >= 5:
        continue
      my_num_days -= 1
    return my_start_date

disclaimer: untested.

  • Related