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

2024-04-24 19:59:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

# 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

它给出了一个熊猫.t系列.索引.日期时间索引

^{pr2}$

但你需要一份名单,让你知道你在忙什么

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系列或数据帧(Get business days between start and end date using pandasCounting the business days between two series


Tags: andofthepandasdatetimedateholidaysbusiness