Python / Pandas / Numpy - Direct calculation of number of business days between two dates excluding holidays

后端 未结 2 2160
我寻月下人不归
我寻月下人不归 2021-02-14 21:30

Is there a better / more direct way to calculate this than the following?

# 1. Set up the start and end date for which you         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 21:49

    If you put the index you created in a dataframe, you can use resample to fill in the gaps. The offset passed to .resample() can include things like business days and even (custom) calendars:

    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
    

    The size of the index - 1 then gives us the amount of days.

提交回复
热议问题