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

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


当前回答

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==今天输出:错误除非这是一个月的最后一天。

其他回答

使用datetime月包。

$ pip install datetime-month
$ python
>>> from month import XMonth
>>> Xmonth(2022, 11).last_date()
datetime.date(2022, 11, 30)

这是一个很长(容易理解)的版本,但考虑了闰年。

def last_day_month(year, month):
    leap_year_flag = 0
    end_dates = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    # Checking for regular leap year    
    if year % 4 == 0:
        leap_year_flag = 1
    else:
        leap_year_flag = 0

    # Checking for century leap year    
    if year % 100 == 0:
        if year % 400 == 0:
            leap_year_flag = 1
        else:
            leap_year_flag = 0
    else:
        pass

    # return end date of the year-month
    if leap_year_flag == 1 and month == 2:
        return 29
    elif leap_year_flag == 1 and month != 2:
        return end_dates[month]
    else:
        return end_dates[month]

下面是一个基于python lambdas的解决方案:

next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)

next_month lambda查找下个月第一天的元组表示形式,并滚动到下一年。month_end lambda将日期(dte)转换为元组,应用next_month并创建新日期。那么“月底”就是下个月的第一天减去时间增量(天=1)。

我认为这比其他一些答案更具可读性:

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)

我在这里找到了有趣的解决方案。提供这些相对的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