有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
在下面的代码中,“get_last_day_of_month(dt)”将为您提供此信息,日期格式为“YYYY-MM-DD”。
import datetime
def DateTime( d ):
return datetime.datetime.strptime( d, '%Y-%m-%d').date()
def RelativeDate( start, num_days ):
d = DateTime( start )
return str( d + datetime.timedelta( days = num_days ) )
def get_first_day_of_month( dt ):
return dt[:-2] + '01'
def get_last_day_of_month( dt ):
fd = get_first_day_of_month( dt )
fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
return RelativeDate( fd_next_month, -1 )
其他回答
编辑:看看我的另一个答案。它有一个比这个更好的实现,我把它放在这里,以防有人有兴趣看到如何“运行自己的”计算器。
@约翰·米利金给出了一个很好的答案,但计算下个月的第一天又增加了复杂性。
以下内容不是特别优雅,但要计算出任何给定日期所在月份的最后一天,您可以尝试:
def last_day_of_month(date):
if date.month == 12:
return date.replace(day=31)
return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)
>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)
如果不想导入日历模块,还可以使用简单的两步功能:
import datetime
def last_day_of_month(any_day):
# The day 28 exists in every month. 4 days later, it's always next month
next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
# subtracting the number of the current day brings us back one month
return next_month - datetime.timedelta(days=next_month.day)
输出:
>>> for month in range(1, 13):
... print(last_day_of_month(datetime.date(2022, month, 1)))
...
2022-01-31
2022-02-28
2022-03-31
2022-04-30
2022-05-31
2022-06-30
2022-07-31
2022-08-31
2022-09-30
2022-10-31
2022-11-30
2022-12-31
如果您需要获得一个月的第一天的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月,以及另一个问题日期,工作正常。
如果只有今天是一个月的最后一天,而日期并不重要,那么我更喜欢使用下面的条件。
逻辑很简单。如果明天是下个月的第一天,那么今天就是实际月份的最后一天。下面是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
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)