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

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


当前回答

如果只有今天是一个月的最后一天,而日期并不重要,那么我更喜欢使用下面的条件。

逻辑很简单。如果明天是下个月的第一天,那么今天就是实际月份的最后一天。下面是if-else条件的两个示例。

from datetime import datetime, timedelta

if (datetime.today()+timedelta(days=1)).day == 1:
    print("today is the last day of the month")
else:
    print("today isn't the last day of the month")

如果时区意识很重要。

from datetime import datetime, timedelta
import pytz

set(pytz.all_timezones_set)
tz = pytz.timezone("Europe/Berlin")

dt = datetime.today().astimezone(tz=tz)

if (dt+timedelta(days=1)).day == 1:
    print("today is the last day of the month")
else:
    print("today isn't the last day of the month")

其他回答

我的方法:

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'

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

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

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

import datetime

now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)

另一个解决方案是这样做:

from datetime import datetime

def last_day_of_month(year, month):
    """ Work out the last day of the month """
    last_days = [31, 30, 29, 28, 27]
    for i in last_days:
        try:
            end = datetime(year, month, i)
        except ValueError:
            continue
        else:
            return end.date()
    return None

使用如下函数:

>>> 
>>> last_day_of_month(2008, 2)
datetime.date(2008, 2, 29)
>>> last_day_of_month(2009, 2)
datetime.date(2009, 2, 28)
>>> last_day_of_month(2008, 11)
datetime.date(2008, 11, 30)
>>> last_day_of_month(2008, 12)
datetime.date(2008, 12, 31)

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