Python calendar.monthrange() Function
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.
Syntax
Following is the syntax of the Python calendar.monthrange() function −
calendar.monthrange(year, month)
Parameters
This function accepts the following parameters −
- year: The year of the month to be checked.
- month: The month (1-12) to be checked.
Return Value
This function returns a tuple (first_weekday, num_days), where −
- first_weekday: An integer (0=Monday, 6=Sunday) representing the first day of the month.
- num_days: The total number of days in the month.
Example: Getting First Weekday and Number of Days
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: 31
Example: 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: 29
Example: 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