有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
这是我的方式-一个只有两行的函数:
from dateutil.relativedelta import relativedelta
def last_day_of_month(date):
return date.replace(day=1) + relativedelta(months=1) - relativedelta(days=1)
例子:
from datetime import date
print(last_day_of_month(date.today()))
>> 2021-09-30
其他回答
在Python 3.7中,有一个未记录的calendar.monthlen(年,月)函数:
>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28
它相当于记录的日历。monthrange(年,月)[1]调用。
编辑:看看我的另一个答案。它有一个比这个更好的实现,我把它放在这里,以防有人有兴趣看到如何“运行自己的”计算器。
@约翰·米利金给出了一个很好的答案,但计算下个月的第一天又增加了复杂性。
以下内容不是特别优雅,但要计算出任何给定日期所在月份的最后一天,您可以尝试:
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)
我的方法:
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'
我认为这比其他一些答案更具可读性:
from datetime import timedelta as td
from datetime import datetime as dt
today = dt.now()
a_day_next_month = dt(today.year, today.month, 27) + td(days=5)
first_day_next_month = dt(a_day_next_month.year, a_day_next_month.month, 1)
last_day_this_month = first_day_next_month - td(days=1)
编辑:查看@Blair Conrad的答案以获得更清洁的解决方案
>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)