有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
最简单的方法是使用日期时间和一些日期数学,例如从下个月的第一天减去一天:
import datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return (
datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
datetime.timedelta(days=1)
)
或者,您可以使用calendar.monthrange()获取一个月的天数(考虑闰年)并相应地更新日期:
import calendar, datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return d.replace(day=calendar.monthrange(d.year, d.month)[1])
快速的基准测试表明,第一个版本明显更快:
In [14]: today = datetime.date.today()
In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
其他回答
如果您愿意使用外部库,请查看http://crsmithdev.com/arrow/
然后,您可以通过以下方式获得本月的最后一天:
import arrow
arrow.utcnow().ceil('month').date()
这将返回一个日期对象,然后可以进行操作。
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)
如果只有今天是一个月的最后一天,而日期并不重要,那么我更喜欢使用下面的条件。
逻辑很简单。如果明天是下个月的第一天,那么今天就是实际月份的最后一天。下面是if-else条件的两个示例。
from datetime import datetime, timedelta
if (datetime.today()+timedelta(days=1)).day == 1:
print("today is the last day of the month")
else:
print("today isn't the last day of the month")
如果时区意识很重要。
from datetime import datetime, timedelta
import pytz
set(pytz.all_timezones_set)
tz = pytz.timezone("Europe/Berlin")
dt = datetime.today().astimezone(tz=tz)
if (dt+timedelta(days=1)).day == 1:
print("today is the last day of the month")
else:
print("today isn't the last day of the month")
我喜欢这样
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将新日期移到上一个日期,这正好是当前月份的最后一个日期。