finding last business day of a month in python

前端 未结 6 1124
半阙折子戏
半阙折子戏 2020-12-31 08:33

I\'m trying to find last business day of of the month. I wrote the code below for that and it works fine but I was wondering if there is a cleaner way of doing it?

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 09:05

    I use this for the first business day of the month but it can be used for last business day of the month as well:

    import time
    import datetime
    from pandas.tseries.holiday import USFederalHolidayCalendar
    from pandas.tseries.offsets import CustomBusinessDay
    from dateutil.relativedelta import relativedelta
    
    #Create dates needed to be entered as parameters
    today = datetime.date.today()
    first = today.replace(day=1)
    #End of the Prior Month
    eopm = first - datetime.timedelta(days=1)
    eopm = eopm.strftime("%Y%m%d")
    #Create first business day of current month date
    us_bd = CustomBusinessDay(calendar=USFederalHolidayCalendar())
    focm = first
    nxtMo = today + relativedelta(months=+1)
    fonm = nxtMo.replace(day=1)
    eocm = fonm - datetime.timedelta(days=1)
    first_bd = pd.DatetimeIndex(start = focm, end = eocm, freq= us_bd)
    first_bd = first_bd.strftime("%Y%m%d")
    #First Business Day of the Month
    first_bd = first_bd[0]
    #Last Business Day of the Month
    lst_day = len(first_bd)-1
    last_bd = first_bd[lst_day]
    

    I left some code in there that is not needed for the last business day of the current month, but may be useful to someone.

提交回复
热议问题