Reputation: 4807
I am trying to figure out a way to generate first and last business day for each week between two dates for example 2016-01-01
and 2017-02-28
.
Considering there are many weeks in US where we have long weekend starting on Friday
or extending to Monday
, finding all dates with Monday and Friday is not a working logic. For weeks where Monday
is holiday, Tuesday
would be first business date and if Friday
is holiday, Thursday
will be last business date.
I can use pandas date_range
function to generate all days between two dates but beyond that I can't seem to figure.
Upvotes: 4
Views: 1409
Reputation: 720
Hello this code should solve the issue:
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
dr = pd.date_range(start='2016-01-01', end='2017-02-28')
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start=dr.min(), end=dr.max())
A = dr[~dr.isin(holidays)] # make sure its not US holiday
B = A[A.weekday != 5] # make sure its not saturday
B = B[B.weekday != 6] # make sure its not saturday
for year in set(B.year): # for every year in your range
tmp = B[B.year == year] # slice it year wise
for week in set(tmp.week): # for each week in slice
temp = tmp[tmp.week == week]
print(temp[temp.weekday == temp.weekday.min()]) # begining of week
print(temp[temp.weekday == temp.weekday.max()]) # ending of week
So basically you import calendar with US holidays, create a desired date range, slice date range based on calendar, then get rid off Saturdays and Sundays and then loop through it and return start and end for each week in date range. Hope it helps!
Upvotes: 3