Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most recent previous business day in Python

I need to subtract business days from the current date.

I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some pretty clunky code to do this:

 lastBusDay = datetime.datetime.today()  if datetime.date.weekday(lastBusDay) == 5:      #if it's Saturday      lastBusDay = lastBusDay - datetime.timedelta(days = 1) #then make it Friday  elif datetime.date.weekday(lastBusDay) == 6:      #if it's Sunday      lastBusDay = lastBusDay - datetime.timedelta(days = 2); #then make it Friday 

Is there a better way?

Can I tell timedelta to work in weekdays rather than calendar days for example?

like image 359
Thomas Browne Avatar asked Feb 08 '10 20:02

Thomas Browne


People also ask

How do I find previous business days?

The previous business day is the most recent prior day on which banks were open for business. Business days are Monday through Friday, not including holidays. For example, on a Tuesday, you would see Monday's transactions. On a Monday, you would see the previous Friday's transactions.


2 Answers

Use pandas!

import datetime # BDay is business day, not birthday... from pandas.tseries.offsets import BDay  today = datetime.datetime.today() print(today - BDay(4)) 

Since today is Thursday, Sept 26, that will give you an output of:

datetime.datetime(2013, 9, 20, 14, 8, 4, 89761) 
like image 136
Kyle Hannon Avatar answered Sep 24 '22 21:09

Kyle Hannon


If you want to skip US holidays as well as weekends, this worked for me (using pandas 0.23.3):

import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar from pandas.tseries.offsets import CustomBusinessDay US_BUSINESS_DAY = CustomBusinessDay(calendar=USFederalHolidayCalendar()) july_5 = pd.datetime(2018, 7, 5) result = july_5 - 2 * US_BUSINESS_DAY # 2018-7-2 

To convert to a python date object I did this:

result.to_pydatetime().date() 
like image 44
lakenen Avatar answered Sep 22 '22 21:09

lakenen