有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?

如果标准库不支持,dateutil包是否支持此功能?


当前回答

如果不想导入日历模块,还可以使用简单的两步功能:

import datetime

def last_day_of_month(any_day):
    # The day 28 exists in every month. 4 days later, it's always next month
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
    # subtracting the number of the current day brings us back one month
    return next_month - datetime.timedelta(days=next_month.day)

输出:

>>> for month in range(1, 13):
...     print(last_day_of_month(datetime.date(2022, month, 1)))
...
2022-01-31
2022-02-28
2022-03-31
2022-04-30
2022-05-31
2022-06-30
2022-07-31
2022-08-31
2022-09-30
2022-10-31
2022-11-30
2022-12-31

其他回答

迄今为止,我找到的最简单、最可靠的方法是:

from datetime import datetime
import calendar
days_in_month = calendar.monthrange(2020, 12)[1]
end_dt = datetime(2020, 12, days_in_month)

我喜欢这样

import datetime
import calendar

date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)

使用dateutil.rrelatedelta

dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)

months=1,days=1将dt移到下个月的第一个日期,然后days=-1将新日期移到上一个日期,这正好是当前月份的最后一个日期。

import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

输出:

31

这将打印当前月份的最后一天。在本例中,是2016年5月15日。因此,您的输出可能不同,但输出的天数与当前月份的天数相同。如果您想通过运行每日cron作业来检查当月的最后一天,那就太好了。因此:导入日历从时间导入gmtime,strftimelastDay=calendar.monthrange(int(strftime(“%Y”,gmtime())),int(strttime(“-m”,gmtime())今天=strftime(“%d”,gmtime())lastDay==今天输出:错误除非这是一个月的最后一天。

我在这里找到了有趣的解决方案。提供这些相对的elta参数,可以得到一个月的最后一天:day=31,days=+1,seconds=-1(这是前一天的最后一秒):

import datetime
from dateutil.relativedelta import relativedelta

day_of_febuary = datetime.datetime(2022, 2, 21)
last_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)
print(last_day_of_febuary)
# Output: 2022-02-28 23:59:59