Skip to main content

calendar — General Calendar-Related Functions

📚 Official Documentation & Resources

Primary Official Sources (REQUIRED)

Additional Authoritative Sources

IMPORTANT: Examples in this guide are adapted from the official Python documentation at https://docs.python.org/3/library/calendar.html

Overview

The calendar module allows you to output calendars like the Unix cal program, and provides additional calendar-related functions. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). This module was available since Python 1.4 and provides both text and HTML calendar generation capabilities.

The module defines several useful classes and functions:

  • Calendar - Base calendar class for flexible date calculations
  • TextCalendar - Plain text calendar generation
  • HTMLCalendar - HTML calendar generation
  • LocaleTextCalendar and LocaleHTMLCalendar - Locale-aware versions

🎯 Key Characteristics

  • Flexible Week Start: Configure first day of week (Monday=0, Sunday=6)
  • Multiple Output Formats: Text, HTML, and programmatic access
  • Locale Support: Locale-aware calendar generation with proper month/day names
  • Date Calculations: Utilities for leap years, month ranges, and day calculations
  • Iterator Support: Iterate over days, weeks, months, and years
  • Thread Safety: Module functions are thread-safe for read operations

🔧 Prerequisites and Setup

Python Version Compatibility

  • Minimum Python version required: Python 1.4+ (module introduction)
  • HTML calendar support: Python 2.2+
  • Locale calendar support: Python 2.5+

Installation and Imports

# Standard library (no installation needed)
import calendar
from calendar import Calendar, TextCalendar, HTMLCalendar

📚 Basic Usage

Official Documentation Examples

Source: All examples adapted from https://docs.python.org/3/library/calendar.html

Simple Example

import calendar

# Print a calendar for a specific month
print(calendar.month(2025, 6))
# June 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

# Print a calendar for an entire year
print(calendar.calendar(2025))

# Check if a year is a leap year
print(calendar.isleap(2024)) # True
print(calendar.isleap(2025)) # False

Core Methods/Functions

# Calendar generation (from official docs)
import calendar

# Text calendar for a month
cal = calendar.TextCalendar(firstweekday=6) # Sunday first
print(cal.formatmonth(2025, 6))

# Get month calendar as nested lists
month_calendar = calendar.monthcalendar(2025, 6)
print(month_calendar)
# [[0, 0, 0, 0, 0, 0, 1], [2, 3, 4, 5, 6, 7, 8], ...]

# Get day of week for a specific date
day_of_week = calendar.weekday(2025, 6, 14)
print(day_of_week) # 5 (Saturday, where Monday=0)

Common Patterns

# Pattern 1: Basic calendar display (from official docs)
import calendar

# Set locale for proper day/month names
calendar.setfirstweekday(calendar.SUNDAY)
print(calendar.month(2025, 6))

# Pattern 2: HTML calendar generation (from official docs)
html_cal = calendar.HTMLCalendar(firstweekday=6)
html_output = html_cal.formatmonth(2025, 6)
print(html_output)

# Pattern 3: Date range calculations (from official docs)
# Get all Fridays in June 2025
import calendar
fridays = []
cal = calendar.monthcalendar(2025, 6)
for week in cal:
if week[calendar.FRIDAY] != 0:
fridays.append(week[calendar.FRIDAY])
print(f"Fridays in June 2025: {fridays}") # [6, 13, 20, 27]

🔧 calendar API Reference

Module Functions

FunctionDescriptionReturn TypeExample
calendar(year, w=2, l=1, c=6)Multi-column year calendarstrcalendar.calendar(2025)
month(year, month, w=0, l=0)Month calendarstrcalendar.month(2025, 6)
monthcalendar(year, month)Month as nested listsList[List[int]]calendar.monthcalendar(2025, 6)
monthrange(year, month)First weekday and number of daysTuple[int, int]calendar.monthrange(2025, 6)
weekday(year, month, day)Day of week (0=Monday)intcalendar.weekday(2025, 6, 14)
isleap(year)Check if year is leap yearboolcalendar.isleap(2024)
leapdays(y1, y2)Number of leap days in rangeintcalendar.leapdays(2020, 2030)
weekheader(n)Week day names headerstrcalendar.weekheader(3)

Calendar Class Methods

MethodDescriptionReturn TypeExample
iterweekdays()Iterator over week daysIterator[int]list(cal.iterweekdays())
itermonthdates(year, month)Iterator over month datesIterator[date]list(cal.itermonthdates(2025, 6))
itermonthdays(year, month)Iterator over month daysIterator[int]list(cal.itermonthdays(2025, 6))
itermonthdays2(year, month)Iterator over (day, weekday) pairsIterator[Tuple]list(cal.itermonthdays2(2025, 6))
monthdayscalendar(year, month)Month as day numbersList[List[int]]cal.monthdayscalendar(2025, 6)
monthdays2calendar(year, month)Month as (day, weekday) pairsList[List[Tuple]]cal.monthdays2calendar(2025, 6)

TextCalendar Class Methods

MethodDescriptionReturn TypeExample
formatmonth(year, month, w=0, l=0)Format month as textstrcal.formatmonth(2025, 6)
formatyear(year, w=2, l=1, c=6, m=3)Format year as textstrcal.formatyear(2025)
prmonth(year, month, w=0, l=0)Print month calendarNonecal.prmonth(2025, 6)
pryear(year, w=2, l=1, c=6, m=3)Print year calendarNonecal.pryear(2025)

HTMLCalendar Class Methods

MethodDescriptionReturn TypeExample
formatmonth(year, month, withyear=True)Format month as HTMLstrcal.formatmonth(2025, 6)
formatyear(year, width=3)Format year as HTMLstrcal.formatyear(2025)
formatmonthname(year, month, withyear=True)Format month name as HTMLstrcal.formatmonthname(2025, 6)

Constants

ConstantValueDescription
MONDAY0Monday weekday constant
TUESDAY1Tuesday weekday constant
WEDNESDAY2Wednesday weekday constant
THURSDAY3Thursday weekday constant
FRIDAY4Friday weekday constant
SATURDAY5Saturday weekday constant
SUNDAY6Sunday weekday constant

Detailed Method Examples

Basic Calendar Display

import calendar

# Official docs example: Display calendar with custom settings
calendar.setfirstweekday(calendar.SUNDAY)
print(calendar.month(2025, 6))

# Get month information
first_weekday, num_days = calendar.monthrange(2025, 6)
print(f"June 2025 starts on {calendar.day_name[first_weekday]} and has {num_days} days")
# June 2025 starts on Sunday and has 30 days

HTML Calendar Generation

import calendar

# Official docs example: Generate HTML calendar
class CustomHTMLCalendar(calendar.HTMLCalendar):
def formatday(self, day, weekday):
if day == 0:
return '<td class="noday">&nbsp;</td>'
else:
return f'<td class="day">{day}</td>'

cal = CustomHTMLCalendar(firstweekday=6)
html = cal.formatmonth(2025, 6)
print(html)

Date Iteration and Calculations

import calendar
from datetime import date

# Official docs example: Find all Mondays in a month
cal = calendar.Calendar(firstweekday=6)
mondays = []
for week in cal.monthdayscalendar(2025, 6):
if week[1] != 0: # Monday is index 1 when Sunday is first day
mondays.append(week[1])

print(f"Mondays in June 2025: {mondays}") # [2, 9, 16, 23, 30]

# Iterate over all dates in a month
for date_obj in cal.itermonthdates(2025, 6):
if date_obj.month == 6: # Only dates in current month
print(f"{date_obj}: {calendar.day_name[date_obj.weekday()]}")

Locale-Aware Calendars

import calendar
import locale

# Official docs example: Locale-specific calendar
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
cal = calendar.LocaleTextCalendar(firstweekday=6, locale='en_US.UTF-8')
print(cal.formatmonth(2025, 6))
except locale.Error:
print("Locale not available, using default")
cal = calendar.TextCalendar(firstweekday=6)
print(cal.formatmonth(2025, 6))

Important Notes

Common Gotchas

  • Week numbering: weekday() returns 0 for Monday, but some applications expect 1-based numbering
  • Month boundaries: monthcalendar() includes padding days from adjacent months as 0
  • Locale sensitivity: Month and day names depend on system locale settings

Performance Considerations

  • Calendar generation is generally fast for single months/years
  • For bulk operations, consider caching Calendar instances
  • HTML calendar generation has more overhead than text calendars

Best Practices

# Use constants instead of magic numbers
calendar.weekday(2025, 6, 14) == calendar.SATURDAY # Better than == 5

# Cache calendar instances for repeated use
cal = calendar.Calendar(firstweekday=calendar.SUNDAY)
# Use cal for multiple operations

# Handle locale gracefully
try:
cal = calendar.LocaleTextCalendar(locale='desired_locale')
except:
cal = calendar.TextCalendar() # Fallback to default

Timezone Considerations

  • The calendar module works with dates only, not times or timezones
  • For timezone-aware date operations, combine with datetime and zoneinfo modules
  • All calculations assume the proleptic Gregorian calendar
  • datetime: For complete date/time handling with timezone support
  • time: For time-related functions and formatting
  • locale: For internationalization and locale-specific formatting