我试图找到这个月的最后一个工作日。我为此编写了下面的代码并且工作正常,但我想知道是否有更清洁的方法呢?
x <- seq(1,1, length.out=10)
y <- seq(0,0, length.out=10)
z <- c(x, y)
p <- c(1,0,1,1,0,0)
提前致谢!
答案 0 :(得分:9)
我使用以下内容:
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 :(得分:3)
单线球迷:
import calendar
def last_business_day_in_month(year: int, month: int) -> int:
return max(calendar.monthcalendar(year, month)[-1:][0][:5])
答案 2 :(得分:2)
假设您希望获得本月的最后一个工作日,直到接下来的两年结束,以下工作将会有效。
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')
答案 3 :(得分:0)
您可以使用Pandas
来获取工作日。请参阅http://pandas.pydata.org/pandas-docs/stable/timeseries.html
此外,您可以参考此https://pypi.python.org/pypi/business_calendar/进行简单的工作日计算。
答案 4 :(得分:0)
我在本月的第一个工作日使用此功能,但它也可用于该月的最后一个工作日:
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]
我在那里留下了一些代码,这些代码在当月的最后一个工作日不需要,但可能对某些人有用。
答案 5 :(得分:0)
如果前一天的日期超过当月的最后一个工作日,则使用rollforward(d),您将跳至下个月,因此以下内容对于该月的任何一天都可能更安全:
from datetime import date
import pandas as pd
d = date(2011, 12, 31) # a caturday
pd.bdate_range(end=pd.offsets.MonthEnd().rollforward(d), periods=1)
pd.offsets.BMonthEnd().rollforward(d)
答案 6 :(得分:0)
我需要一些直观易读的内容,并选择了以下内容:
from datetime import datetime, timedelta
import pandas as pd
def isMonthLastBusinessDay(date):
lastDayOfMonth = date + pd.offsets.MonthEnd(0)
isFriday = date.weekday() == 4
if (date.weekday() < 5 and lastDayOfMonth == date) or (isFriday and lastDayOfMonth == date+timedelta(days=1)) or (isFriday and lastDayOfMonth == date+timedelta(days=2)):
return True
else:
return False