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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With