Python Calendar


Python’s calendar module is a built-in library that provides tools to work with dates, months, and calendars. Whether you want to display a calendar for a specific month, check if a year is a leap year, or determine the day of the week for a given date, the calendar module makes it simple and efficient. This module is widely used in scheduling applications, date validation, and generating calendar views for web or desktop programs.

In this tutorial, we will explore how to create calendars, access month and year information, work with weekdays, iterate over days, and generate formatted calendars. We will also look at practical examples for real-world applications.

Importing the calendar Module

The calendar module is built into Python, so no installation is required. To use it, import the module:

import calendar

You can also import specific functions or classes:

from calendar import month, isleap, monthcalendar

This approach helps keep your code cleaner by importing only what you need.

Displaying a Calendar

Displaying a Full Year

You can display the calendar of an entire year using the calendar() function:

year_calendar = calendar.calendar(2025)
print(year_calendar)

The output will display all 12 months of the year with weekdays properly aligned, making it easier to plan events or visualize the year.

Displaying a Single Month

To display a specific month, use the month() function:

print(calendar.month(2025, 11))

This will display November 2025 in a structured, readable format:

   November 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

You can immediately see weekdays, weekends, and total days, which is useful for planning schedules.

Getting the Weekday of a Date

The weekday() function returns the day of the week as an integer where Monday is 0 and Sunday is 6:

day = calendar.weekday(2025, 11, 20)
print(day)  # Output: 3

You can map this to a string for readability:

weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(weekdays[day])  # Output: Thursday

First Day and Total Days of a Month

The monthrange() function provides both the first weekday and the number of days in a month:

first_day, total_days = calendar.monthrange(2025, 11)
print(first_day, total_days)  # Output: 5 30

Here, first_day is the weekday index of the first day (0=Monday) and total_days is the number of days in the month. This is useful for custom calendar generation.

Leap Year Operations

Leap years have 366 days instead of 365, and the calendar module provides easy functions to handle them.

Check if a Year is a Leap Year

print(calendar.isleap(2024))  # Output: True
print(calendar.isleap(2025))  # Output: False

Count Leap Years in a Range

print(calendar.leapdays(2000, 2025))  # Output: 6

This helps in date calculations where leap years affect durations.

Customizing the Calendar

By default, calendars start with Monday as the first day. You can change this using setfirstweekday():

calendar.setfirstweekday(calendar.SUNDAY)
print(calendar.month(2025, 11))

This is useful for regional calendar formats, where some countries start the week on Sunday.

Iterating Over Days of a Month

You can iterate over all days in a month using itermonthdays():

for day in calendar.itermonthdays(2025, 11):
    print(day, end=' ')

Days outside the month are represented as 0, which is helpful for grid-based calendar displays.

Calendar Classes

Python provides classes for more advanced calendar formatting.

TextCalendar

TextCalendar allows formatted text calendars:

cal = calendar.TextCalendar(calendar.MONDAY)
print(cal.formatmonth(2025, 11))

HTMLCalendar

HTMLCalendar creates HTML formatted calendars, useful for web applications:

cal = calendar.HTMLCalendar(calendar.SUNDAY)
html_calendar = cal.formatmonth(2025, 11)
print(html_calendar)

You can also generate full-year HTML calendars using formatyear().

Practical Examples

  1. Display the current month:

from calendar import month
from datetime import datetime

today = datetime.today()
print(month(today.year, today.month))
  1. Check if a year is a leap year:

year = 2024
if calendar.isleap(year):
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")
  1. Find the weekday of a specific date:

weekday_index = calendar.weekday(2025, 11, 20)
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print("The day is:", weekdays[weekday_index])
  1. List all Mondays in a month:

cal = calendar.monthcalendar(2025, 11)
mondays = [week[0] for week in cal if week[0] != 0]
print("Mondays in November 2025:", mondays)
  1. Generate a full-year HTML calendar:

html_cal = calendar.HTMLCalendar(calendar.MONDAY)
print(html_cal.formatyear(2025))
  1. Print weekdays header:

print(calendar.weekheader(3))  # Output: Mon Tue Wed Thu Fri Sat Sun

Summary of the Tutorial

The Python calendar module is a versatile and easy-to-use tool for managing dates, months, weekdays, and years. It allows you to:

  • Display formatted calendars for months and years

  • Determine the day of the week for a specific date

  • Check leap years and count leap days

  • Customize the first day of the week for regional calendars

  • Generate text and HTML formatted calendars for desktop or web applications

By mastering the calendar module, you can create scheduling applications, validate dates, generate calendar views, and perform date-related calculations efficiently. It is an essential tool for any Python programmer working with time-based applications.


Practice Questions

  1. Print the calendar of the year 2025 using the calendar module.

  2. Display the calendar for November 2025 using calendar.month().

  3. Check if the year 2024 is a leap year.

  4. Find out the weekday of 20th November 2025.

  5. List all Mondays in November 2025 using monthcalendar().

  6. Change the first day of the week to Sunday and display November 2025.

  7. Print the header of weekdays with 3-character abbreviations using weekheader().

  8. Generate a full-year HTML calendar for 2025 using HTMLCalendar.

  9. Count the number of leap years between 2000 and 2025.

  10. Display a text calendar for November 2025 using TextCalendar.formatmonth().


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top