Home >Backend Development >Python Tutorial >How to Get the Last Day of Any Month in Python?

How to Get the Last Day of Any Month in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 03:06:12886browse

How to Get the Last Day of Any Month in Python?

Get the Last Day of the Month in Python

Python provides a straightforward method to determine the last day of a given month using its standard library. The calendar module offers a function called calendar.monthrange that returns two pieces of information: the weekday of the first day of the month and the number of days in that month.

To obtain the last day of a month, simply access the second element of the tuple returned by calendar.monthrange:

last_day = calendar.monthrange(year, month)[1]

Here are a few examples to illustrate its usage:

>>> import calendar
>>> calendar.monthrange(2002, 1)
(6, 31)  # Tuesday, 31 days in January

>>> calendar.monthrange(2008, 2)
(4, 29)  # Friday, 29 days in a leap year's February

>>> calendar.monthrange(2100, 2)
(0, 28)  # Monday, 28 days in a non-leap year's February

The calendar module handles leap years correctly, as demonstrated in the second example. It also supports both past and future dates, as well as pre-Georgian calendars. However, for Python versions prior to 3.12, the weekday is displayed as an integer in the interactive Python shell, as seen in the last example.

The above is the detailed content of How to Get the Last Day of Any Month in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn