ZetCode

Python calendar module

last modified November 19, 2026 Python 3.15

In this article we work with the calendar module in Python. The module prints text and HTML calendars and provides functions for leap years, month lengths, and weekdays.

The module uses the proleptic Gregorian calendar: the current calendar, extended backwards and forwards indefinitely. By default, weeks start on Monday, as in ISO 8601. Weekdays are numbered from 0 for Monday to 6 for Sunday, the same as date.weekday from the datetime module.

A month calendar

The calendar.month function returns a month calendar as a multi-line string.

month_calendar.py
import calendar

text = calendar.month(2026, 11)
print(text)

The calendar has a title, a header with abbreviated weekday names, and one line per week. November 2026 begins on a Sunday, so the first week has only one day.

$ python month_calendar.py
   November 2026
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

The first day of the week

In the United States and some other countries, weeks begin on Sunday. The TextCalendar class takes the first weekday as a parameter.

first_weekday.py
import calendar

us = calendar.TextCalendar(firstweekday=calendar.SUNDAY)
print(us.formatmonth(2026, 11))

wide = calendar.TextCalendar()
print(wide.formatmonth(2026, 11, w=3))

print(calendar.firstweekday())
calendar.setfirstweekday(calendar.SUNDAY)
print(calendar.firstweekday())

The calendar.SUNDAY constant is 6. The w parameter of formatmonth sets the width of a day column; with three characters, the header shows three-letter names. The module-level functions such as calendar.month use a global setting, which setfirstweekday changes. A TextCalendar object keeps its own setting, which is safer in larger programs.

$ python first_weekday.py
   November 2026
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

       November 2026
Mon Tue Wed Thu Fri Sat Sun
                          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

0
6

Leap years

The isleap function tells whether a year is a leap year and leapdays counts the leap years in a range.

leap_years.py
import calendar

for year in [1900, 2000, 2024, 2026, 2028, 2100]:
    print(year, calendar.isleap(year))

print(calendar.leapdays(2000, 2101))

leap = [y for y in range(2020, 2050) if calendar.isleap(y)]
print(leap)

A year divisible by 4 is a leap year, except for years divisible by 100, unless they are also divisible by 400. So 2000 was a leap year, while 1900 and 2100 are not. The leapdays function counts the leap years from the first year up to, but not including, the second one.

$ python leap_years.py
1900 False
2000 True
2024 True
2026 False
2028 True
2100 False
25
[2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048]

Month lengths

The monthrange function returns the weekday of the first day of a month and the number of days in it.

month_lengths.py
import calendar
from datetime import date

first, days = calendar.monthrange(2026, 2)
print(first, days)
print(calendar.day_name[first])

for month in range(1, 13):
    print(calendar.month_abbr[month], calendar.monthrange(2026, month)[1], end="  ")
print()


def last_day(d):
    return d.replace(day=calendar.monthrange(d.year, d.month)[1])


print(last_day(date(2028, 2, 10)))
print(last_day(date(2026, 11, 19)))

try:
    calendar.monthrange(2026, 13)
except calendar.IllegalMonthError as e:
    print(type(e).__mro__[1].__name__, "-", e)

February 2026 starts on a Sunday and has 28 days. The month_abbr sequence holds the abbreviated month names. With the number of days, replace moves any date to the last day of its month, which handles February in leap years. An invalid month raises IllegalMonthError, a subclass of ValueError.

$ python month_lengths.py
6 28
Sunday
Jan 31  Feb 28  Mar 31  Apr 30  May 31  Jun 30  Jul 31  Aug 31  Sep 30  Oct 31  Nov 30  Dec 31  
2028-02-29
2026-11-30
ValueError - bad month number 13; must be 1-12

Names and enums

The module provides the names of weekdays and months, and since Python 3.12 the Day and Month enumerations.

names_enums.py
import calendar

print(list(calendar.day_name))
print(list(calendar.day_abbr))
print(list(calendar.month_name))

print(calendar.weekday(2026, 11, 19))
print(calendar.day_name[calendar.weekday(2026, 11, 19)])

day = calendar.Day(calendar.weekday(2026, 11, 19))
print(day, day.name, day.value)

month = calendar.Month.NOVEMBER
print(month, month.value, month == 11)
print([m.name[:3].title() for m in calendar.Month if m.value % 3 == 0])

The month_name sequence has an empty string at index 0, so that month numbers index it directly. The names follow the current locale. The weekday function returns the weekday of a date. The Day and Month enums are IntEnum classes: they compare equal to plain numbers and print as numbers, but also have names. The old constants such as calendar.FRIDAY are now members of Day.

$ python names_enums.py
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
3
Thursday
3 THURSDAY 3
11 11 True
['Mar', 'Jun', 'Sep', 'Dec']

The nth weekday of a month

Many holidays fall on the nth weekday of a month, such as the fourth Thursday of November. The monthcalendar function returns a month as a list of weeks, which makes them easy to find.

nth_weekday.py
import calendar
from datetime import date

weeks = calendar.monthcalendar(2026, 11)
for week in weeks:
    print(week)


def nth_weekday(year, month, weekday, n):
    days = [week[weekday] for week in calendar.monthcalendar(year, month)
            if week[weekday]]
    return date(year, month, days[n - 1 if n > 0 else n])


print("Thanksgiving:", nth_weekday(2026, 11, calendar.THURSDAY, 4))
print("Mother's Day:", nth_weekday(2026, 5, calendar.SUNDAY, 2))
print("last Monday in May:", nth_weekday(2026, 5, calendar.MONDAY, -1))

for month in range(1, 13):
    print(nth_weekday(2026, month, calendar.FRIDAY, 2), end=" ")
print()

Each week is a list of seven day numbers; days that belong to other months are 0. Taking one column of the matrix and dropping the zeros gives all the Thursdays, for example. The nth_weekday function counts from 1, and negative numbers count from the end: -1 is the last Monday. The loop prints the second Friday of every month in 2026.

$ python nth_weekday.py
[0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]
Thanksgiving: 2026-11-26
Mother's Day: 2026-05-10
last Monday in May: 2026-05-25
2026-01-09 2026-02-13 2026-03-13 2026-04-10 2026-05-08 2026-06-12 2026-07-10 2026-08-14 2026-09-11 2026-10-09 2026-11-13 2026-12-11 

Iterating over a month

The Calendar class has iterators that return the days of a month in complete weeks, as a calendar sheet shows them.

iterate_month.py
import calendar

cal = calendar.Calendar()

dates = list(cal.itermonthdates(2026, 11))
print(len(dates), dates[0], dates[-1])

print(list(cal.itermonthdays(2026, 11))[:9])
print(list(cal.itermonthdays2(2026, 11))[:9])

for y, m, d, wd in cal.itermonthdays4(2026, 11):
    if m == 11 and wd == calendar.MONDAY:
        print(f"{y}-{m:02}-{d:02}", end=" ")
print()

print([d.isoformat() for d in cal.itermonthdates(2026, 11)
       if d.month == 11 and d.weekday() >= 5][:4])

The itermonthdates method returns date objects for six full weeks, from October 26 to December 6, including days of the neighbouring months. The itermonthdays method returns 0 for those days, itermonthdays2 pairs each day with its weekday, and itermonthdays4 returns year, month, day, and weekday. When using these iterators, filter out the days of other months.

$ python iterate_month.py
42 2026-10-26 2026-12-06
[0, 0, 0, 0, 0, 0, 1, 2, 3]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 6), (2, 0), (3, 1)]
2026-11-02 2026-11-09 2026-11-16 2026-11-23 2026-11-30 
['2026-11-01', '2026-11-07', '2026-11-08', '2026-11-14']

Marking events

The TextCalendar class builds the output from methods that we can override. The following subclass marks days with events.

event_calendar.py
import calendar
from datetime import date

EVENTS = {
    date(2026, 11, 5): "dentist",
    date(2026, 11, 17): "holiday",
    date(2026, 11, 19): "release",
    date(2026, 11, 30): "invoice",
}


class EventCalendar(calendar.TextCalendar):

    def formatmonth(self, year, month, w=3, l=1):
        self.year, self.month = year, month
        return super().formatmonth(year, month, w, l)

    def formatday(self, day, weekday, width):
        if day == 0:
            return " " * width
        if date(self.year, self.month, day) in EVENTS:
            return f"*{day}".rjust(width)
        return str(day).rjust(width)


cal = EventCalendar()
print(cal.formatmonth(2026, 11))

for day, name in sorted(EVENTS.items()):
    print(f"{day:%a %d}  {name}")

The formatday method returns the text of a single day. It receives only the day number, so formatmonth stores the year and month first. Days with an event get an asterisk. Day 0 is a padding cell, which stays blank. The default column width is three, to leave room for the mark.

$ python event_calendar.py
       November 2026
Mon Tue Wed Thu Fri Sat Sun
                          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

Thu 05  dentist
Tue 17  holiday
Thu 19  release
Mon 30  invoice

A year calendar

The calendar.calendar function returns a whole year. Its parameters set the column width w, the lines per week l, the spacing between months c, and the number of months per row m.

year_calendar.py
import calendar

text = calendar.calendar(2026, w=2, l=1, c=4, m=4)
lines = text.splitlines()
print("\n".join(lines[:10]))
print(len(lines))

With four months per row, the year has three blocks of months and 28 lines. The program prints only the first block. Each month in a block takes the same number of lines; March 2026 needs six weeks.

$ python year_calendar.py
                                            2026

      January                 February                 March                   April
Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su
          1  2  3  4                       1                       1           1  2  3  4  5
 5  6  7  8  9 10 11     2  3  4  5  6  7  8     2  3  4  5  6  7  8     6  7  8  9 10 11 12
12 13 14 15 16 17 18     9 10 11 12 13 14 15     9 10 11 12 13 14 15    13 14 15 16 17 18 19
19 20 21 22 23 24 25    16 17 18 19 20 21 22    16 17 18 19 20 21 22    20 21 22 23 24 25 26
26 27 28 29 30 31       23 24 25 26 27 28       23 24 25 26 27 28 29    27 28 29 30
                                                30 31
28

Localized calendars

The LocaleTextCalendar class prints month and weekday names in the language of a given locale.

locale_calendar.py
import calendar

sk = calendar.LocaleTextCalendar(locale="sk_SK.UTF-8")
print(sk.formatmonth(2026, 11))

print(sk.formatweekheader(3))
print(sk.formatweekheader(9))
print(sk.formatmonthname(2026, 2, 20))
print(calendar.month_name[2])

The locale must be installed on the system. The class switches the locale only while formatting, so the module-level month_name stays in English afterwards. The formatweekheader method takes the width of a column and shortens the names to fit it.

$ python locale_calendar.py
   november 2026
Po Ut St Št Pi So Ne
                   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

 Po  Ut  St  Št  Pi  So  Ne
 Pondelok   Utorok    Streda   Štvrtok    Piatok    Sobota    Nedeľa 
    február 2026    
February

HTML calendars

The HTMLCalendar class produces HTML tables. Every cell has a CSS class, so the calendar can be styled.

html_calendar.py
import calendar

cal = calendar.HTMLCalendar()
html = cal.formatmonth(2026, 11)

for line in html.splitlines()[:5]:
    print(line)
print("...")

print(cal.cssclasses)
print(cal.cssclass_month, cal.cssclass_noday)

page = cal.formatyearpage(2026, css="calendar.css")
print(page[:120].decode())

The formatmonth method returns a table with one row per week. Day cells get the class of their weekday from cssclasses, and padding cells the noday class. The formatyearpage method returns a complete HTML page as bytes, with a link to a style sheet. Like TextCalendar, the class can be subclassed to add events to the cells.

$ python html_calendar.py
<table class="month">
<tr><th colspan="7" class="month">November 2026</th></tr>
<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sun">1</td></tr>
<tr><td class="mon">2</td><td class="tue">3</td><td class="wed">4</td><td class="thu">5</td><td class="fri">6</td><td class="sat">7</td><td class="sun">8</td></tr>
...
['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
month noday
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initia

timegm

The calendar.timegm function converts a time tuple in UTC to a Unix timestamp. It is the inverse of time.gmtime.

timegm_example.py
import calendar
import time
from datetime import UTC, datetime

ts = calendar.timegm((2026, 11, 19, 13, 30, 0))
print(ts)
print(time.gmtime(ts)[:6])
print(datetime.fromtimestamp(ts, tz=UTC))

st = time.gmtime(1_800_000_000)
print(calendar.timegm(st))
print(time.mktime(st))

The function reads the first six fields of the tuple. The time.mktime function looks similar but treats the tuple as local time, so in Bratislava in winter the result is 3600 seconds off. The Python time module article covers the time tuples.

$ python timegm_example.py
1795095000
(2026, 11, 19, 13, 30, 0)
2026-11-19 13:30:00+00:00
1800000000
1799996400.0

Friday the 13th

The weekday functions answer calendar questions quickly. Here we look for Fridays falling on the 13th.

fridays_13.py
import calendar
from collections import Counter

found = []
for year in range(2026, 2031):
    for month in range(1, 13):
        if calendar.weekday(year, month, 13) == calendar.FRIDAY:
            found.append(f"{year}-{month:02}-13")

print(len(found), found)

first_days = Counter(calendar.day_abbr[calendar.weekday(year, 1, 1)]
                     for year in range(2001, 2401))
print(first_days)

thirteenths = Counter(calendar.weekday(y, m, 13)
                      for y in range(2001, 2401) for m in range(1, 13))
for wd, count in sorted(thirteenths.items()):
    print(calendar.day_abbr[wd], count)

Between 2026 and 2030 there are nine Fridays the 13th; 2026 alone has three. The Gregorian calendar repeats every 400 years, so counting over one full cycle gives exact frequencies. January 1 falls unevenly on the weekdays, and the 13th of a month falls on a Friday more often than on any other day.

$ python fridays_13.py
9 ['2026-02-13', '2026-03-13', '2026-11-13', '2027-08-13', '2028-10-13', '2029-04-13', '2029-07-13', '2030-09-13', '2030-12-13']
Counter({'Tue': 58, 'Sun': 58, 'Fri': 58, 'Wed': 57, 'Thu': 57, 'Mon': 56, 'Sat': 56})
Mon 685
Tue 685
Wed 687
Thu 684
Fri 688
Sat 684
Sun 687

The command line

The module can be run as a program. It prints a year or a month calendar.

The -f option sets the first weekday, -L the locale, and -t html switches to HTML output. A locale requires the -e encoding option; without it, the program exits with an error. Without arguments it prints the current year.

$ python -m calendar 2026 11
   November 2026
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
$ python -m calendar -f 6 -L sk_SK.UTF-8 -e utf-8 2026 2
    február 2026
Ne Po Ut St Št Pi So
 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

Source

calendar – General calendar-related functions

In this article we have worked with the calendar module in Python. See also Python datetime, Python timedelta, Python ISO weeks, and Python time module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.