How to print a calendar for a month in Python



In Python to display calendar, you need to import calendar module, it provides various functions to handle operations related to calendar, and also includes printing a text calendar for a month .

Calendar Module

The calendar module in python provides various functions and classes to perform date-related operations. To print a calendar in Python, we import the calendar module, which will import all module classes.

Key Features

Some of the features provided by Calendar module are as follows:

  • Calendar Functions: To generate HTML or text format calendars for a given month or year.

  • Locale settings: We can customize the calendar to match with specfic locale sertting such as first day of the week, month names etc.

  • Calculations on Date: We can also Perform calculations with dates, such as finding nmber of weeks in a month.

Example 1

The below example code will print a text calendar for a specified year(yy) and month(mm).

# importing calendar module
import calendar

# Specifying the year and month
year = 2024
month = 8

# Creating a TextCalendar object
cal = calendar.TextCalendar(calendar.SUNDAY)

# Printing calendar for the specified month and year
print(cal.formatmonth(year, month))

Output

     August 2024
Su Mo Tu We Th Fr Sa
             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 2

Printing the calendar by using the calendar.month built-in function.

# Importing the calendar module
import calendar

y = 2024

m = 9
# By using calender.month() function  

print(calendar.month(y, m))

Output

 September 2024
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
Updated on: 2024-09-23T14:22:57+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements