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

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


当前回答

我的方法:

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'

其他回答

更简单地说:

import datetime
now = datetime.datetime.now()
datetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)

对我来说,这是最简单的方法:

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

使用熊猫!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

如果您不介意使用Pandas,那么使用Timestamp.days_in_month可能是最简单的:

import pandas as pd

> pd.Timestamp(year=2020, month=2, day=1).days_in_month

29

calendar.monthrange提供以下信息:

日历.月范围(年,月)返回指定年份和月份的月份第一天的工作日和月份天数。

>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2)  # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren't leap years
(0, 28)

so:

calendar.monthrange(year, month)[1]

似乎是最简单的方法。