Python / Pandas / Numpy - 直接计算两个日期之间的工作日数(不包括假期)

2024-04-26

有没有比下面更好/更直接的方法来计算这个?

# 1. Set up the start and end date for which you want to calculate the      
# number of business days excluding holidays.

start_date = '01JAN1986'
end_date = '31DEC1987'
start_date = datetime.datetime.strptime(start_date, '%d%b%Y')
end_date = datetime.datetime.strptime(end_date, '%d%b%Y')

# 2. Generate a list of holidays over this period
from pandas.tseries.holiday import USFederalHolidayCalendar
calendar = USFederalHolidayCalendar()
holidays = calendar.holidays(start_date, end_date)
holidays

这给出了 pandas.tseries.index.DatetimeIndex

DatetimeIndex(['1986-01-01', '1986-01-20', '1986-02-17', '1986-05-26',
           '1986-07-04', '1986-09-01', '1986-10-13', '1986-11-11',
           '1986-11-27', '1986-12-25', '1987-01-01', '1987-01-19',
           '1987-02-16', '1987-05-25', '1987-07-03', '1987-09-07',
           '1987-10-12', '1987-11-11', '1987-11-26', '1987-12-25'],
          dtype='datetime64[ns]', freq=None, tz=None)

但是你需要一个 numpy Busday_count 的列表

holiday_date_list = holidays.date.tolist()

然后,无论有没有假期,您都会得到:

np.busday_count(start_date.date(), end_date.date()) 
>>> 521

np.busday_count(start_date.date(), end_date.date(), holidays = holiday_date_list)
>>> 501

还有一些其他问题稍微相似,但通常与 pandas Series 或 Dataframes 一起使用(使用 pandas 获取开始日期和结束日期之间的工作日 https://stackoverflow.com/questions/13019719/get-business-days-between-start-and-end-date-using-pandas, 计算两个系列之间的工作日 https://stackoverflow.com/questions/17703436/counting-the-business-days-between-two-series)


如果将创建的索引放入数据框中,则可以使用resample https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling填补空白。偏移量传递给.resample()可以包括工作日甚至(自定义)日历之类的内容:

from pandas.tseries.holiday import USFederalHolidayCalendar

C = pd.offsets.CustomBusinessDay(calendar=USFederalHolidayCalendar())

start_date = '01JAN1986'
end_date = '31DEC1987'

(
pd.DataFrame(index=pd.to_datetime([start_date, end_date]))
    .resample(C, closed='right') 
    .asfreq()
    .index  
    .size
) - 1

索引的大小 - 1 给出了天数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python / Pandas / Numpy - 直接计算两个日期之间的工作日数(不包括假期) 的相关文章

随机推荐