Selected Reading

Python calendar.monthcalendar() Function



The Python calendar.monthcalendar() function is used to generate a matrix representation of a month's calendar.

This function returns a list of weeks, where each week is a list of integers representing days. Days outside the month are represented by zeros.

Syntax

Following is the syntax of the Python calendar.monthcalendar() function โˆ’

calendar.monthcalendar(year, month)

Parameters

This function accepts the following parameters โˆ’

  • year: The year of the month to be displayed.
  • month: The month (1-12) to be displayed.

Return Value

This function returns a list of weeks, where each week is a list of 7 integers. Days that belong to the month are represented by their respective date numbers, and days outside the month are represented by 0.

Example: Getting Month Calendar as a Matrix

In this example, we generate a matrix for March 2025 using the Python calendar.monthcalendar() function โˆ’

import calendar

# Generate March 2025 matrix
month_matrix = calendar.monthcalendar(2025, 3)

print(month_matrix)

Following is the output obtained โˆ’

[[0, 0, 0, 0, 0, 1, 2],
 [3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16],
 [17, 18, 19, 20, 21, 22, 23],
 [24, 25, 26, 27, 28, 29, 30],
 [31, 0, 0, 0, 0, 0, 0]]

Example: Iterating Over the Calendar Matrix

We can iterate over the matrix to display the month in a readable format as shown in the example below โˆ’

import calendar

# Generate March 2025 matrix
month_matrix = calendar.monthcalendar(2025, 3)

for week in month_matrix:
   print(week)

Following is the output of the above code โˆ’

[0, 0, 0, 0, 0, 1, 2]
[3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16]
[17, 18, 19, 20, 21, 22, 23]
[24, 25, 26, 27, 28, 29, 30]
[31, 0, 0, 0, 0, 0, 0]

Example: Checking if a Specific Day is in a Week

We can check if a specific date is in a given week using this function โˆ’

import calendar

# Generate March 2025 matrix
month_matrix = calendar.monthcalendar(2025, 3)

# Check if 15th is in a particular week
for week in month_matrix:
   if 15 in week:
      print("15th March is in this week:", week)

We get the output as shown below โˆ’

15th March is in this week: [10, 11, 12, 13, 14, 15, 16]

Example: Counting Number of Weeks in a Month

We can determine how many weeks exist in a given month using the calendar.monthcalendar() function โˆ’

import calendar

# Generate March 2025 matrix
month_matrix = calendar.monthcalendar(2025, 3)

# Count the number of weeks
num_weeks = len(month_matrix)

print("Number of weeks in March 2025:", num_weeks)

The result produced is as follows โˆ’

Number of weeks in March 2025: 6
python_date_time.htm
Advertisements