从 python 中的年月中获取该月的最后一天

get last day of the month from year month in python

我需要根据给定的年月值获取一个月的第一天和最后一天。我能够得到第一天,我们如何在这里得到这个月的最后一天(python):

from datetime import date
def first_day_of_month(year,month):
    return date(year, month, 1)

print "Today: %s" % date.today()
print ("First day of this month: %s" %
first_day_of_month(2015,10))

这给出了输出: 今天:2015-10-26 本月初一:2015-10-01

如何获取一个月的最后一天? P.s : 我不想将 31 作为 date() 函数的第三个参数。我想计算一个月中的天数,然后将其传递给函数。

使用calendar.monthrange:

from calendar import monthrange
monthrange(2011, 2)
(1, 28)
# Just to be clear, monthrange supports leap years as well:

from calendar import monthrange
monthrange(2012, 2)
(2, 29)

"Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month."