HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Get the last day of the month

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
thegetmonthlastday

Problem

Can Python's standard library (or dateutil if not) easily determine (i.e. one function call) the last day of a given month?

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(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 simply:

calendar.monthrange(year, month)[1]

Code Snippets

calendar.monthrange(year, month)[1]

Context

Stack Overflow Q#42950, score: 1524

Revisions (0)

No revisions yet.