Content · Programming · Python

Python calendar.monthrange() Function: Usage and Examples

Find the weekday of month start and number of days in the month.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Find the weekday of month start and number of days in the month.

How It Works


calendar.monthrange(year, month) returns (first_weekday, number_of_days). Monday is weekday zero, and months must be between 1 and 12.

Step-by-Step Example


import calendar
start_weekday, days_in_month = calendar.monthrange(2026, 2)
print(days_in_month)
print(0 <= start_weekday <= 6)

Understanding the Example


  • The expression 'calendar.monthrange(2026, 2)' supplies the value stored as 'start_weekday, days_in_month'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

28
True

Where This Fits in a Real Program


For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.

Practice: Try It Yourself


The first weekday uses the Monday-zero convention regardless of setfirstweekday().

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Using the weekday integer as if Sunday were zero or forgetting that February changes in leap years.
  • Determine the last valid day of a user-provided month.

Key Takeaways


  • Find the weekday of month start and number of days in the month.
  • calendar.monthrange(year, month) returns (first_weekday, number_of_days).
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.