>>> import calendar>>> calendar.monthrange(2002, 1)(1, 31)>>> calendar.monthrange(2008, 2) # leap years are handled correctly(4, 29)>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years(0, 28)
from datetime import datetime
def last_day_of_month(year, month):""" Work out the last day of the month """last_days = [31, 30, 29, 28, 27]for i in last_days:try:end = datetime(year, month, i)except ValueError:continueelse:return end.date()return None
# Some random date.some_date = datetime.date(2012, 5, 23)
# Get last weekdaylast_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()
print last_weekday31
import datetime
def last_day_of_month(any_day):# The day 28 exists in every month. 4 days later, it's always next monthnext_month = any_day.replace(day=28) + datetime.timedelta(days=4)# subtracting the number of the current day brings us back one monthreturn 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-312022-02-282022-03-312022-04-302022-05-312022-06-302022-07-312022-08-312022-09-302022-10-312022-11-302022-12-31
def eomday(year, month):"""returns the number of days in a given month"""days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]d = days_per_month[month - 1]if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):d = 29return d
import pytzfrom 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 timefist_day_with_time = datetime.combine((now.replace(day=1) - timedelta(days=1)).replace(day=1), datetime.min.time())
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, timedeltaimport 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")
def get_last_day_of_month(mon: int, year: int) -> str:'''Returns last day of the month.'''
### Day 28 falls in every monthres = datetime(month=mon, year=year, day=28)### Go to next monthres = res + timedelta(days=4)### Subtract one day from the start of the next monthres = datetime.strptime(res.strftime('%Y-%m-01'), '%Y-%m-%d') - timedelta(days=1)
return res.strftime('%Y-%m-%d')