Python calendar.month() Function



The Python calendar.month() function is used to generate a month's calendar in a multi-line string format.

This function returns a formatted month calendar as a string, making it easy to display or print a specific month's calendar.

Syntax

Following is the syntax of the Python calendar.month() function −

calendar.month(year, month, w=2, l=1)

Parameters

This function accepts the following parameters −

  • year: The year of the month to be displayed.
  • month: The month (1-12) to be displayed.
  • w (optional): The width of each date column (default is 2).
  • l (optional): The number of lines per week (default is 1).

Return Value

This function returns a multi-line string containing the formatted calendar for the specified month.

Example: Displaying a Month Calendar

In this example, we generate a calendar for March 2025 using the Python calendar.month() function −

import calendar

# Generate March 2025 calendar
month_calendar = calendar.month(2025, 3)

print(month_calendar)

Following is the output obtained −

    March 2025
Mo Tu We Th Fr Sa Su
                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

Example: Customizing Column Width

We can adjust the width of date columns using the w parameter of the month() function −

import calendar

# Generate March 2025 calendar with custom width
month_calendar = calendar.month(2025, 3, w=4)

print(month_calendar)

Following is an excerpt of the customized output −

    March 2025
Mo   Tu   We   Th   Fr   Sa   Su  
                          1    2  
 3    4    5    6    7    8    9  
...

Example: Adjusting Line Spacing

We can modify the line spacing between weeks using the l parameter −

import calendar

# Generate March 2025 calendar with extra spacing
month_calendar = calendar.month(2025, 3, l=2)

print(month_calendar)

Following is output of the above code −

    March 2025
Mo Tu We Th Fr Sa Su
                1  2
  
 3  4  5  6  7  8  9
  
10 11 12 13 14 15 16
...

Example: Displaying a Different Month

We can also use the month() function to display any other month, such as December 2024 −

import calendar

# Generate December 2024 calendar
month_calendar = calendar.month(2024, 12)

print(month_calendar)

We get the output as shown below −

   December 2024
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
...
python_date_time.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy