How to get the last day of the month? How to get the last day of the month? python python

How to get the last day of the month?


calendar.monthrange provides this information:

calendar.monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar>>> calendar.monthrange(2002, 1)(1, 31)>>> calendar.monthrange(2008, 2)  # leap years are handled correctly(4, 29)>>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren't leap years(0, 28)

so:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.


If you don't want to import the calendar module, a simple two-step function can also be:

import datetimedef last_day_of_month(any_day):    # this will never fail    # get close to the end of the month for any day, and add 4 days 'over'    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)    # subtract the number of remaining 'overage' days to get last day of current month, or said programattically said, the previous day of the first of next month    return next_month - datetime.timedelta(days=next_month.day)

Outputs:

>>> for month in range(1, 13):...     print last_day_of_month(datetime.date(2012, month, 1))...2012-01-312012-02-292012-03-312012-04-302012-05-312012-06-302012-07-312012-08-312012-09-302012-10-312012-11-302012-12-31


EDIT: See @Blair Conrad's answer for a cleaner solution


>>> import datetime>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)datetime.date(2000, 1, 31)