我正在尝试找出一种方法来生成两个日期之间每周的第一个和最后一个工作日,例如2016-01-01
和2017-02-28
。
考虑到美国有很多个星期我们在Friday
开始或者延伸到Monday
的长周末,找到星期一和星期五的所有日期都不是一个有效的逻辑。对于Monday
假期的几周,Tuesday
将是第一个营业日期,如果Friday
是假日,则Thursday
将是上次营业日期。
我可以使用pandas date_range
函数生成两个日期之间的所有日子,但除此之外,我无法想象。
答案 0 :(得分:1)
你好这段代码应该解决这个问题:
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
所以基本上你导入美国假期的日历,创建一个所需的日期范围,根据日历切片日期范围,然后摆脱星期六和星期日,然后循环它并返回日期范围内每周的开始和结束。 希望它有所帮助!