Home >Backend Development >Python Tutorial >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
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
If you prefer a succinct expression, you can use the following code snippet:
calendar.monthrange(year, month)[1]
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!