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

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


当前回答

这个对我很有用:

df['daysinmonths'] = df['your_date_col'].apply(lambda t: pd.Period(t, freq='S').days_in_month)

参考来源:https://stackoverflow.com/a/66403016/16607636

其他回答

考虑到不同月份的天数不相等,以下是适用于每个月的标准解决方案。

import datetime
ref_date = datetime.today() # or what ever specified date

end_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)

在上面的代码中,我们只是将一个月添加到所选日期,然后导航到该月的第一天,然后从该日期中减去一天。

使用datetime月包。

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

这是我只使用标准日期时间库的最简单解决方案:

import datetime

def get_month_end(dt):
    first_of_month = datetime.datetime(dt.year, dt.month, 1)
    next_month_date = first_of_month + datetime.timedelta(days=32)
    new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)
    return new_dt - datetime.timedelta(days=1)

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

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

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

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

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