有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
你可以使用relativeltahttps://dateutil.readthedocs.io/en/stable/relativedelta.htmlmonth_end=<您当月的datetime值>+relativelta(day=31)这将给你最后一天。
其他回答
在Python 3.7中,有一个未记录的calendar.monthlen(年,月)函数:
>>> calendar.monthlen(2002, 1)
31
>>> calendar.monthlen(2008, 2)
29
>>> calendar.monthlen(2100, 2)
28
它相当于记录的日历。monthrange(年,月)[1]调用。
这是我只使用标准日期时间库的最简单解决方案:
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)
我喜欢这样
import datetime
import calendar
date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)
使用dateutil.rrelatedelta
dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)
months=1,days=1将dt移到下个月的第一个日期,然后days=-1将新日期移到上一个日期,这正好是当前月份的最后一个日期。
你可以自己计算结束日期。简单的逻辑是从下个月的开始日期减去一天。:)
所以写一个自定义方法,
import datetime
def end_date_of_a_month(date):
start_date_of_this_month = date.replace(day=1)
month = start_date_of_this_month.month
year = start_date_of_this_month.year
if month == 12:
month = 1
year += 1
else:
month += 1
next_month_start_date = start_date_of_this_month.replace(month=month, year=year)
this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
return this_month_end_date
使命感
end_date_of_a_month(datetime.datetime.now().date())
它将返回本月的结束日期。将任何日期传递给此函数。返回该月的结束日期。