4

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.

Data Enthusiast
  • 521
  • 4
  • 12
  • 22
  • 1
    So what have you tried, and what exactly is the problem with it? For example, why not subtract one day from the start of the following month? – jonrsharpe Oct 26 '15 at 19:31
  • I tried calendar method to get monthrange, and that way I could do it but I wanted to use date function as I used that for first day. below method suggested by @Busturdust is what I was looking for – Data Enthusiast Oct 26 '15 at 19:42

1 Answers1

11

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

KT12
  • 549
  • 11
  • 24
Busturdust
  • 2,447
  • 24
  • 41
  • 5
    You may want to explain the return value of `monthrange`: "Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month." (So OP would want `month_end = monthrange(year, month)[1]`.) Your `datetime` solution requires extra logic to handle the first and last month of the year. I would omit it as the `monthrange` solution is more than adequate. Also, you have a typo -- you have a backtick before `from`. – Steven Rumbalski Oct 26 '15 at 19:42