get last day of the month from year month in python

Data Enthusiast picture Data Enthusiast · Oct 26, 2015 · Viewed 14.2k times · Source

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) :

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

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.

Answer

Busturdust picture Busturdust · Oct 26, 2015

Use 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."