有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
使用熊猫!
def isMonthEnd(date):
return date + pd.offsets.MonthEnd(0) == date
isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False
其他回答
最简单的方法是使用日期时间和一些日期数学,例如从下个月的第一天减去一天:
import datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return (
datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
datetime.timedelta(days=1)
)
或者,您可以使用calendar.monthrange()获取一个月的天数(考虑闰年)并相应地更新日期:
import calendar, datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return d.replace(day=calendar.monthrange(d.year, d.month)[1])
快速的基准测试表明,第一个版本明显更快:
In [14]: today = datetime.date.today()
In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
在Python 3.7中,有一个未记录的calendar.monthlen(年,月)函数:
>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28
它相当于记录的日历。monthrange(年,月)[1]调用。
编辑:查看@Blair Conrad的答案以获得更清洁的解决方案
>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)
这个对我很有用:
df['daysinmonths'] = df['your_date_col'].apply(lambda t: pd.Period(t, freq='S').days_in_month)
参考来源:https://stackoverflow.com/a/66403016/16607636
我的方法:
def get_last_day_of_month(mon: int, year: int) -> str:
'''
Returns last day of the month.
'''
### Day 28 falls in every month
res = datetime(month=mon, year=year, day=28)
### Go to next month
res = res + timedelta(days=4)
### Subtract one day from the start of the next month
res = datetime.strptime(res.strftime('%Y-%m-01'), '%Y-%m-%d') - timedelta(days=1)
return res.strftime('%Y-%m-%d')
>>> get_last_day_of_month(mon=10, year=2022)
... '2022-10-31'