从python的一年中获取月份的最后一天[复制]

时间:2022-09-27 20:18:34

This question already has an answer here:

这个问题在这里已有答案:

I need to get first and last day of a month based on the given yearmonth value. I am able to get the first day, how do we get the last day of the month here ( 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))

This gives the output: Today: 2015-10-26 First day of this month: 2015-10-01

这给出了输出:今天:2015-10-26这个月的第一天:2015-10-01

How to fetch the last day of the month? P.s : I do not want to give 31 as the third parameter for date() function. I want to calculate number of days in the month and then pass on that to the function.

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

1 个解决方案

#1


7  

Use calendar.monthrange:

使用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."

“返回工作日(0-6~周一至周日)和年,月的天数(28-31)。”

#1


7  

Use calendar.monthrange:

使用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."

“返回工作日(0-6~周一至周日)和年,月的天数(28-31)。”