Python Tutorial (33) – Example: Calculating the number of days in each month

Time: Column:Python views:352

Python Code to Calculate the Number of Days in a Month Using the calendar Module

The following Python code demonstrates how to use the calendar module to calculate the number of days in a given month and find out which day of the week the month starts on.

Example: Calculate Days in a Month

# Import the calendar module
import calendar

# Get the month range for September 2016
monthRange = calendar.monthrange(2016, 9)

# Print the result
print(monthRange)

Sample Output:

(3, 30)

Explanation:

  • The result is a tuple where:

    • The first element (3) indicates that September 2016 starts on a Thursday (0 is Monday, 6 is Sunday).

    • The second element (30) indicates that September 2016 has 30 days.

This code helps you easily determine the starting day of any month and its total number of days using Python's calendar module.