有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
有没有一种方法可以使用Python的标准库轻松确定(即一个函数调用)给定月份的最后一天?
如果标准库不支持,dateutil包是否支持此功能?
当前回答
如果您愿意使用外部库,请查看http://crsmithdev.com/arrow/
然后,您可以通过以下方式获得本月的最后一天:
import arrow
arrow.utcnow().ceil('month').date()
这将返回一个日期对象,然后可以进行操作。
其他回答
如果只有今天是一个月的最后一天,而日期并不重要,那么我更喜欢使用下面的条件。
逻辑很简单。如果明天是下个月的第一天,那么今天就是实际月份的最后一天。下面是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")
from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
如果您不介意使用Pandas,那么使用Timestamp.days_in_month可能是最简单的:
import pandas as pd
> pd.Timestamp(year=2020, month=2, day=1).days_in_month
29
另一种选择是使用递归函数。
第二天是在不同的月份吗?如果是,则当前日期是该月的最后一天。如果第二天在同一个月,请使用第二天重试。
from datetime import timedelta
def last_day_of_month(date):
if date.month != (date + timedelta(days=1)).month:
return date
else:
return last_day_of_month(date + timedelta(days=1))
这是一个很长(容易理解)的版本,但考虑了闰年。
def last_day_month(year, month):
leap_year_flag = 0
end_dates = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
# Checking for regular leap year
if year % 4 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
# Checking for century leap year
if year % 100 == 0:
if year % 400 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
else:
pass
# return end date of the year-month
if leap_year_flag == 1 and month == 2:
return 29
elif leap_year_flag == 1 and month != 2:
return end_dates[month]
else:
return end_dates[month]