Dec 9 2012

Python: Last Date of the Month

A usual case I’ve seen time and again is some permutation of getting the end of the month date. In Python, this can be a one-liner using the calendar module. The following does a test if a given date represents the last day of the month:

 

>>> import calendar
>>> given_date.day == calendar.monthrange(given_date.year, given_date.month)[1]

 

The calendar module’s monthrange method takes a year and month parameters. It returns the weekday of the first day of the month and number of days in month, for the specified year and month.