The Python calendar.monthrange() function returns a tuple containing the first weekday of the month and the number of days in the month.
This function is useful for determining the starting weekday and length of a given month.
SyntaxFollowing is the syntax of the Python calendar.monthrange() function −
calendar.monthrange(year, month)Parameters
This function accepts the following parameters −
This function returns a tuple (first_weekday, num_days), where −
In this example, we get the details for March 2025 using the calendar.monthrange() function −
import calendar # Get first weekday and number of days in March 2025 first_day, num_days = calendar.monthrange(2025, 3) print("First weekday:", first_day) print("Number of days:", num_days)
Following is the output obtained −
First weekday: 5 Number of days: 31Example: Checking if a Month Starts on a Specific Day
We can check if a month starts on a given weekday as shown in the example below −
import calendar # Get first weekday for March 2025 first_day, _ = calendar.monthrange(2025, 3) # Check if it starts on a Monday if first_day == calendar.MONDAY: print("March 2025 starts on a Monday.") else: print("March 2025 does not start on a Monday.")
Following is the output of the above code −
March 2025 does not start on a Monday.Example: Getting the Last Day of a Month
We can use the monthrange() function to find the last day of a month as follows −
import calendar # Get number of days in February 2024 _, num_days = calendar.monthrange(2024, 2) print("Last day of February 2024:", num_days)
We get the output as shown below −
Last day of February 2024: 29Example: Iterating Over Months in a Year
We can iterate over all months of a year to print their first weekday and number of days −
import calendar # Iterate through all months of 2025 for month in range(1, 13): first_day, num_days = calendar.monthrange(2025, month) print(f"Month {month}: First weekday = {first_day}, Days = {num_days}")
The result produced is as shown below −
Month 1: First weekday = 2, Days = 31 Month 2: First weekday = 5, Days = 28 Month 3: First weekday = 5, Days = 31 ... Month 12: First weekday = 1, Days = 31
python_date_time.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4