有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
我在这里找到了有趣的解决方案。提供这些相对的elta参数,可以得到一个月的最后一天:day=31,days=+1,seconds=-1(这是前一天的最后一秒):
import datetime
from dateutil.relativedelta import relativedelta
day_of_febuary = datetime.datetime(2022, 2, 21)
last_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)
print(last_day_of_febuary)
# Output: 2022-02-28 23:59:59
其他回答
使用dateutil.rrelatedelta
dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)
months=1,days=1将dt移到下个月的第一个日期,然后days=-1将新日期移到上一个日期,这正好是当前月份的最后一个日期。
这是另一个答案。无需额外包装。
datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(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())
它将返回本月的结束日期。将任何日期传递给此函数。返回该月的结束日期。
使用dateutil.relativedelta,您可以获得如下月份的最后一个日期:
from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)
这个想法是在一个月的第一天,使用relativelta提前一个月,然后返回一天,这样你就能得到你想要的一个月最后一天。
我在这里找到了有趣的解决方案。提供这些相对的elta参数,可以得到一个月的最后一天:day=31,days=+1,seconds=-1(这是前一天的最后一秒):
import datetime
from dateutil.relativedelta import relativedelta
day_of_febuary = datetime.datetime(2022, 2, 21)
last_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)
print(last_day_of_febuary)
# Output: 2022-02-28 23:59:59