Home > Backend Development > Python Tutorial > How Can I Efficiently Determine the Last Day of Any Month in Python?

How Can I Efficiently Determine the Last Day of Any Month in Python?

Barbara Streisand
Release: 2024-12-05 00:31:12
Original
642 people have browsed it

How Can I Efficiently Determine the Last Day of Any Month in Python?

Determining the Last Day of a Month in Python

For developers seeking an efficient and straightforward approach to find the last day of a particular month using Python's standard library, calendar.monthrange comes to the rescue. This function returns an array with two elements: the weekday of the first day of the month and the number of days in that month.

import calendar

# Get last day of January 2002
last_day_of_jan_2002 = calendar.monthrange(2002, 1)[1]  # Result: 31
Copy after login

Handling leap years is also seamless, as demonstrated in the example below:

# Get last day of February 2008 (leap year)
last_day_of_feb_2008 = calendar.monthrange(2008, 2)[1]  # Result: 29
Copy after login

If you prefer a succinct expression, you can use the following code snippet:

calendar.monthrange(year, month)[1]
Copy after login

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

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template