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)
    (calendar.TUESDAY, 31)
    
    >>> calendar.monthrange(2008, 2)  # leap years are handled correctly
    (calendar.FRIDAY, 29)
    
    >>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren't leap years
    (calendar.MONDAY, 28)
    
    # the module uses the Georgian calendar extended into the past and
    # future, so leap days in the distant past will differ from Julian:
    >>> calendar.monthrange(1100, 2)
    (calendar.THURSDAY, 28)
    
    # note also that pre-Python 3.12, the REPL renders the weekday
    # as a bare integer:
    >>> calendar.monthrange(2002, 1)
    (1, 31)
    

    so:

    calendar.monthrange(year, month)[1]
    

    seems like the simplest way to go.