Pandas forming first and last working day of every week between two dates
I'm trying to figure out a way to create the first and last workday for each week between two dates, like 2016-01-01
and 2017-02-28
.
Given that there are many weeks in the US where we have long weekends starting with Friday
or extending to Monday
, finding all dates from Monday to Friday is not working logic. During the weeks when it Monday
is a holiday, this Tuesday
will be the first business date, and if it Friday
is a holiday, it Thursday
will be the last business date.
I can use a function pandas date_range
to generate all days between two dates, but beyond that I can't seem to.
source to share
Hello, this code should solve the problem:
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 a calendar for US holidays, create the date range you want, date range based on the calendar, and then get rid of Saturday and Sunday, and then project it and return the start and end for each week in the date range. Hope this helps!
source to share