2

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
2
  • Can you write a version that can only go backwards? Commented Mar 28, 2022 at 23:38
  • Yes, I can use a function that subtracts the business days as well. Would like a single one that does both, but at this point, I'll take anything. Commented Mar 28, 2022 at 23:39

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.