Get Last Day of the Month in Python
Is there a way using Python's standard library to easily determine (ie one function call) the last day of a given month?
If the standard library doesn't support that, does the dateutil package support this?
I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:
monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month.
>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)
so:
calendar.monthrange(year, month)[1]
seems like the simplest way to go.
Just to be clear, monthrange
supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
My previous answer still works, but is clearly suboptimal.
If you don't want to import the calendar
module, a simple two-step function can also be:
import datetime
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail
return next_month - datetime.timedelta(days=next_month.day)
Outputs:
>>> for month in range(1, 13):
... print last_day_of_month(datetime.date(2012, month, 1))
...
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
2012-06-30
2012-07-31
2012-08-31
2012-09-30
2012-10-31
2012-11-30
2012-12-31
编辑:请参阅@Blair康拉德的答案为更清洁的解决方案
>>> import datetime
>>> datetime.date (2000, 2, 1) - datetime.timedelta (days = 1)
datetime.date(2000, 1, 31)
>>>
链接地址: http://www.djcxy.com/p/18478.html
上一篇: 如何从日期中减去一天?
下一篇: 用Python获取本月的最后一天