Showing posts with label days in month. Show all posts
Showing posts with label days in month. Show all posts

Saturday, December 13, 2014

How to get the number of days in a month

LastDayOfTheMonth
In [1]:
import calendar
In [2]:
help(calendar.monthrange)
Help on function monthrange in module calendar:

monthrange(year, month)
    Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
    year, month.


In [3]:
"""
This returns a tuple.
the first item in the tuple is the weekday that
the month starts on and the second item is the
number of days in the month.
"""
calendar.monthrange(2014,12)
Out[3]:
(0, 31)
In [4]:
#select the second item in the tuple only
#i.e. the number of days in the month
calendar.monthrange(2014,12)[1]
Out[4]:
31
In [5]:
#another example, using November
calendar.monthrange(2014,11)[1]
Out[5]:
30
In [6]:
#another example, using October
calendar.monthrange(2014,10)[1]
Out[6]:
31