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:
JavaScript
x
6
1
lastBusDay = datetime.datetime.today()
2
if datetime.date.weekday(lastBusDay) == 5: #if it's Saturday
3
lastBusDay = lastBusDay - datetime.timedelta(days = 1) #then make it Friday
4
elif datetime.date.weekday(lastBusDay) == 6: #if it's Sunday
5
lastBusDay = lastBusDay - datetime.timedelta(days = 2); #then make it Friday
6
Is there a better way?
Can I tell timedelta to work in weekdays rather than calendar days for example?
Advertisement
Answer
Use pandas!
JavaScript
1
7
1
import datetime
2
# BDay is business day, not birthday...
3
from pandas.tseries.offsets import BDay
4
5
today = datetime.datetime.today()
6
print(today - BDay(4))
7
Since today is Thursday, Sept 26, that will give you an output of:
JavaScript
1
2
1
datetime.datetime(2013, 9, 20, 14, 8, 4, 89761)
2