0
0
PythonHow-ToBeginner · 3 min read

How to Find Number of Days in a Month in Python

You can find the number of days in a month in Python using the calendar.monthrange(year, month) function, which returns the weekday of the first day and the number of days in that month. Alternatively, use datetime with timedelta to calculate days by moving to the next month and subtracting dates.
📐

Syntax

The most common way is using the calendar.monthrange(year, month) function.

  • year: The full year as an integer (e.g., 2024).
  • month: The month as an integer from 1 (January) to 12 (December).
  • The function returns a tuple: (weekday of first day, number of days in month).
python
import calendar

# Syntax:
weekday, days_in_month = calendar.monthrange(year, month)
💻

Example

This example shows how to get the number of days in February 2024 using calendar.monthrange.

python
import calendar

year = 2024
month = 2
_, days = calendar.monthrange(year, month)
print(f"Number of days in {month}/{year}: {days}")
Output
Number of days in 2/2024: 29
⚠️

Common Pitfalls

One common mistake is to assume all months have the same number of days or to forget leap years affect February's length. Using calendar.monthrange handles leap years correctly.

Another pitfall is passing invalid month numbers (like 0 or 13), which will cause errors.

python
import calendar

# Wrong: month 13 does not exist
try:
    calendar.monthrange(2024, 13)
except ValueError as e:
    print(f"Error: {e}")

# Right: valid month
_, days = calendar.monthrange(2024, 12)
print(f"Days in December 2024: {days}")
Output
Error: bad month number 13 Days in December 2024: 31
📊

Quick Reference

Summary tips for finding days in a month:

  • Use calendar.monthrange(year, month) for a quick and reliable answer.
  • Remember months are numbered 1 to 12.
  • Leap years are handled automatically.
  • Check for valid month input to avoid errors.

Key Takeaways

Use calendar.monthrange(year, month) to get the number of days in a month easily.
The function returns a tuple; the second value is the days count.
Months must be between 1 and 12 to avoid errors.
Leap years are automatically handled by calendar.monthrange.
Always validate input to prevent exceptions.