On this page
  1. calendar
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Iterating Dates in a Month (Calendar.itermonthdates)
  7. 2. Finding the Last Day of Any Month
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

calendar

Prev: cProfile | Up: stdlib_module | Next: cmath
Rel: datetime, zoneinfo, collections, heapq, bisect
Ref: docs.python.org — calendar
Tags: #public #python3 #stdlib


Import

import calendar

Overview

Gregorian calendar calculations, weekday/month iterators, leap-year checks (isleap, monthrange, monthcalendar), and plain-text/HTML calendar rendering. Pair calendar with datetime when computing month lengths, billing-cycle boundaries, or weekly grid layouts.

Quick Start

import calendar

assert calendar.isleap(2024) and not calendar.isleap(2026)
first_weekday, num_days = calendar.monthrange(2026, 12)
assert num_days == 31
assert calendar.day_name[first_weekday] == "Tuesday"

Implementation Walkthrough

1. Iterating Dates in a Month (Calendar.itermonthdates)

Calendar(firstweekday=calendar.SUNDAY) yields full weeks of datetime.date objects (including leading/trailing padding days from adjacent months) for building calendar UIs:

import calendar

cal = calendar.Calendar(firstweekday=calendar.SUNDAY)
dec_days = [d for d in cal.itermonthdates(2026, 12) if d.month == 12]
assert len(dec_days) == 31 and dec_days[0].day == 1 and dec_days[-1].day == 31

2. Finding the Last Day of Any Month

import calendar
from datetime import date

def month_end(year: int, month: int) -> date:
    _, last_day = calendar.monthrange(year, month)
    return date(year, month, last_day)

assert month_end(2024, 2) == date(2024, 2, 29)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes