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

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

Mary-Kate Olsen
Release: 2024-12-01 22:01:11
Original
160 people have browsed it

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

Determining the Last Day of a Month in Python

Determining the last day of a given month is a common task in programming. Python's standard library provides a convenient way to obtain this information with a single function call.

The calendar module contains the monthrange function that takes two arguments: the year and the month. It returns a tuple with two pieces of information: the weekday of the first day of the month and the number of days in the month. To obtain the last day of the month, we can extract the second value from the tuple:

import calendar

year = 2023
month = 1

# Get the number of days in January 2023
last_day = calendar.monthrange(year, month)[1]

print("Last day of January 2023:", last_day)
Copy after login

This will output:

Last day of January 2023: 31
Copy after login

The monthrange function handles leap years correctly. It also supports dates beyond the Gregorian calendar's current range. However, it's important to note that the dateutil package does not offer any additional functionality for determining the last day of the month, as the calendar module already provides a robust implementation for this task.

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

source:php.cn
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