有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
对我来说,这是最简单的方法:
selected_date = date(some_year, some_month, some_day)
if selected_date.month == 12: # December
last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)
其他回答
如果你想制作自己的小功能,这是一个很好的起点:
def eomday(year, month):
"""returns the number of days in a given month"""
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
d = days_per_month[month - 1]
if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
d = 29
return d
为此,您必须了解闰年的规则:
每四年除了每100年但每400年一次
对我来说,更简单的方法是使用panda(两行解决方案):
from datetime import datetime
import pandas as pd
firstday_month = datetime(year, month, 1)
lastday_month = firstday_month + pd.offsets.MonthEnd(1)
另一种方法是:取一个月的第一天,然后再加一个月,再折一天:
from datetime import datetime
import pandas as pd
firstday_month = datetime(year, month, 1)
lastday_month = firstday_month + pd.DateOffset(months=1) - pd.DateOffset(days=1)
最简单的方法是使用日期时间和一些日期数学,例如从下个月的第一天减去一天:
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)
这个对我很有用:
df['daysinmonths'] = df['your_date_col'].apply(lambda t: pd.Period(t, freq='S').days_in_month)
参考来源:https://stackoverflow.com/a/66403016/16607636
编辑:看看我的另一个答案。它有一个比这个更好的实现,我把它放在这里,以防有人有兴趣看到如何“运行自己的”计算器。
@约翰·米利金给出了一个很好的答案,但计算下个月的第一天又增加了复杂性。
以下内容不是特别优雅,但要计算出任何给定日期所在月份的最后一天,您可以尝试:
def last_day_of_month(date):
if date.month == 12:
return date.replace(day=31)
return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)
>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)