Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last day of the month from year month in python [duplicate]

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.

like image 649
Data Enthusiast Avatar asked Dec 18 '22 22:12

Data Enthusiast


1 Answers

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

like image 82
Busturdust Avatar answered May 16 '23 07:05

Busturdust