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)
This will output:
Last day of January 2023: 31
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!