Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 379
cyberbrain Avatar asked Oct 02 '12 13:10

cyberbrain


People also ask

How do I add business days to a date in Python?

Use the import numpy as np statement to import the numpy module in your Python file. Create a start date and end date using the datetime. date() class of a datetime module. The busday_count() function counts the number of business days between the start date and end date, not including the day of the end dates.

How do I add days to a datetime in Python?

Use the timedelta() class from the datetime module to add days to a date, e.g. result_1 = date_1 + timedelta(days=3) .


2 Answers

Skipping weekends would be pretty easy doing something like this:

import datetime def date_by_adding_business_days(from_date, add_days):     business_days_to_add = add_days     current_date = from_date     while business_days_to_add > 0:         current_date += datetime.timedelta(days=1)         weekday = current_date.weekday()         if weekday >= 5: # sunday = 6             continue         business_days_to_add -= 1     return current_date  #demo: print '10 business days from today:' print date_by_adding_business_days(datetime.date.today(), 10) 

The problem with holidays is that they vary a lot by country or even by region, religion, etc. You would need a list/set of holidays for your use case and then skip them in a similar way. A starting point may be the calendar feed that Apple publishes for iCal (in the ics format), the one for the US would be http://files.apple.com/calendars/US32Holidays.ics

You could use the icalendar module to parse this.

like image 153
omz Avatar answered Oct 03 '22 03:10

omz


If you don't mind using a 3rd party library then dateutil is handy

from dateutil.rrule import * print "In 4 business days, it's", rrule(DAILY, byweekday=(MO,TU,WE,TH,FR))[4] 

You can also look at rruleset and using .exdate() to provide the holidays to skip those in the calculation, and optionally there's a cache option to avoid re-calculating that might be worth looking in to.

like image 41
Jon Clements Avatar answered Oct 03 '22 05:10

Jon Clements