Search code examples
pythondate

Get the last day of the month


Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?


Solution

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