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

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


当前回答

如果您需要获得一个月的第一天的0:00时间,并且不想导入任何特殊的库,您可以这样写

import pytz
from datetime import datetime, timedelta

# get now time with timezone (optional)
now = datetime.now(pytz.UTC)

# get first day on this month, get last day on prev month and after get first day on prev month with min time
fist_day_with_time = datetime.combine((now.replace(day=1) - timedelta(days=1)).replace(day=1), datetime.min.time())

2月28日至29日,12月至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==今天输出:错误除非这是一个月的最后一天。

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)

如果传入日期范围,则可以使用以下命令:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res

我的方法:

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'

对我来说,更简单的方法是使用panda(两行解决方案):

    from datetime import datetime
    import pandas as pd

    firstday_month = datetime(year, month, 1)
    lastday_month = firstday_month + pd.offsets.MonthEnd(1)

另一种方法是:取一个月的第一天,然后再加一个月,再折一天:

    from datetime import datetime
    import pandas as pd

    firstday_month = datetime(year, month, 1)
    lastday_month = firstday_month + pd.DateOffset(months=1) - pd.DateOffset(days=1)