finding last business day of a month in python
我想找一个月的最后一个工作日。我为这个写了下面的代码,它工作得很好,但是我想知道是否有一种更清洁的方法来做它?
1 2 3 4 5 6 7 8 9 10 11 12 13 | from datetime import date,timedelta import datetime import calendar today=datetime.date.today() last = today.replace(day=calendar.monthrange(today.year,today.month)[1]) if last.weekday()<5: print last else: print last-timedelta(days=1+last.weekday()-5) |
事先谢谢!
我使用以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 | from pandas.tseries.offsets import BMonthEnd from datetime import date d=date.today() offset = BMonthEnd() #Last day of current month offset.rollforward(d) #Last day of previous month offset.rollback(d) |
比如说,你想把一个月的最后一个工作日安排到下两年年底,下面的工作就可以了。
1 2 3 4 5 6 | import pandas as pd import datetime start = datetime.date.today() end = datetime.date(start.year+2, 12, 31) bussiness_days_rng =pd.date_range(start, end, freq='BM') |
我在本月的第一个工作日使用此功能,但也可用于本月的最后一个工作日:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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] |
我在其中留下了一些代码,这些代码对于当月的最后一个工作日是不需要的,但可能对某些人有用。
您可以使用
此外,您还可以参考https://pypi.python.org/pypi/business_calendar/了解简单的工作日计算。