calendar — General Calendar-Related Functions
📚 Official Documentation & Resources
Primary Official Sources (REQUIRED)
- Python Official Library Documentation: https://docs.python.org/3/library/calendar.html
- Python Official Tutorial: https://docs.python.org/3/tutorial/index.html
- Module Source Code: https://github.com/python/cpython/blob/main/Lib/calendar.py
Additional Authoritative Sources
- Real Python - Working with Dates: https://realpython.com/python-datetime/
- GeeksforGeeks - Python Calendar: https://www.geeksforgeeks.org/python-calendar-module/
- Python Module of the Week (PyMOTW) - calendar: https://pymotw.com/3/calendar/
- Stack Overflow calendar questions: https://stackoverflow.com/questions/tagged/python+calendar
- "Python Standard Library" by Doug Hellmann
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 calculationsTextCalendar- Plain text calendar generationHTMLCalendar- HTML calendar generationLocaleTextCalendarandLocaleHTMLCalendar- 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
| Function | Description | Return Type | Example |
|---|---|---|---|
calendar(year, w=2, l=1, c=6) | Multi-column year calendar | str | calendar.calendar(2025) |
month(year, month, w=0, l=0) | Month calendar | str | calendar.month(2025, 6) |
monthcalendar(year, month) | Month as nested lists | List[List[int]] | calendar.monthcalendar(2025, 6) |
monthrange(year, month) | First weekday and number of days | Tuple[int, int] | calendar.monthrange(2025, 6) |
weekday(year, month, day) | Day of week (0=Monday) | int | calendar.weekday(2025, 6, 14) |
isleap(year) | Check if year is leap year | bool | calendar.isleap(2024) |
leapdays(y1, y2) | Number of leap days in range | int | calendar.leapdays(2020, 2030) |
weekheader(n) | Week day names header | str | calendar.weekheader(3) |
Calendar Class Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
iterweekdays() | Iterator over week days | Iterator[int] | list(cal.iterweekdays()) |
itermonthdates(year, month) | Iterator over month dates | Iterator[date] | list(cal.itermonthdates(2025, 6)) |
itermonthdays(year, month) | Iterator over month days | Iterator[int] | list(cal.itermonthdays(2025, 6)) |
itermonthdays2(year, month) | Iterator over (day, weekday) pairs | Iterator[Tuple] | list(cal.itermonthdays2(2025, 6)) |
monthdayscalendar(year, month) | Month as day numbers | List[List[int]] | cal.monthdayscalendar(2025, 6) |
monthdays2calendar(year, month) | Month as (day, weekday) pairs | List[List[Tuple]] | cal.monthdays2calendar(2025, 6) |
TextCalendar Class Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
formatmonth(year, month, w=0, l=0) | Format month as text | str | cal.formatmonth(2025, 6) |
formatyear(year, w=2, l=1, c=6, m=3) | Format year as text | str | cal.formatyear(2025) |
prmonth(year, month, w=0, l=0) | Print month calendar | None | cal.prmonth(2025, 6) |
pryear(year, w=2, l=1, c=6, m=3) | Print year calendar | None | cal.pryear(2025) |
HTMLCalendar Class Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
formatmonth(year, month, withyear=True) | Format month as HTML | str | cal.formatmonth(2025, 6) |
formatyear(year, width=3) | Format year as HTML | str | cal.formatyear(2025) |
formatmonthname(year, month, withyear=True) | Format month name as HTML | str | cal.formatmonthname(2025, 6) |
Constants
| Constant | Value | Description |
|---|---|---|
MONDAY | 0 | Monday weekday constant |
TUESDAY | 1 | Tuesday weekday constant |
WEDNESDAY | 2 | Wednesday weekday constant |
THURSDAY | 3 | Thursday weekday constant |
FRIDAY | 4 | Friday weekday constant |
SATURDAY | 5 | Saturday weekday constant |
SUNDAY | 6 | Sunday 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"> </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
Calendarinstances - 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
calendarmodule works with dates only, not times or timezones - For timezone-aware date operations, combine with
datetimeandzoneinfomodules - All calculations assume the proleptic Gregorian calendar
Related Modules
- datetime: For complete date/time handling with timezone support
- time: For time-related functions and formatting
- locale: For internationalization and locale-specific formatting