Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Add OR Subtract N *Business* Days from Date Input

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading