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

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


当前回答

这是另一个答案。无需额外包装。

datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)

取下个月的第一天,从中减去一天。

其他回答

我的方法:

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'

编辑:查看@Blair Conrad的答案以获得更清洁的解决方案


>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)
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==今天输出:错误除非这是一个月的最后一天。

下面是一个基于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)。

如果您愿意使用外部库,请查看http://crsmithdev.com/arrow/

然后,您可以通过以下方式获得本月的最后一天:

import arrow
arrow.utcnow().ceil('month').date()

这将返回一个日期对象,然后可以进行操作。