2 min read

Python Calendar Module

The calendar module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention).

Importing the Module

import calendar

Displaying Calendars

Text Calendar

You can generate a plain text calendar for a specific month or year.

import calendar

# Create a TextCalendar instance
c = calendar.TextCalendar(calendar.SUNDAY)

# Print a month's calendar
str_month = c.formatmonth(2023, 10)
print(str_month)

You can also use module-level functions for quick output.

# Print the calendar for a specific month
print(calendar.month(2023, 10))

# Print the calendar for a whole year
print(calendar.calendar(2023))

HTML Calendar

The module can also generate HTML calendars.

import calendar

hc = calendar.HTMLCalendar(calendar.SUNDAY)
str_month = hc.formatmonth(2023, 10)
print(str_month)

Iterating Over Dates

monthcalendar()

Returns a matrix representing a month's calendar. Each row represents a week; days outside of the month are represented by zeros.

import calendar

matrix = calendar.monthcalendar(2023, 10)
print(matrix)
# Output: [[0, 0, 0, 0, 0, 0, 1], [2, 3, 4, 5, 6, 7, 8], ...]

itermonthdates()

Returns an iterator for the month (as datetime.date objects). This includes days from the previous and next months to complete the weeks.

import calendar

c = calendar.Calendar()
for date in c.itermonthdates(2023, 10):
    print(date)

Leap Years

isleap()

Returns True if year is a leap year, otherwise False.

import calendar

print(calendar.isleap(2020)) # False
print(calendar.isleap(2024)) # True

leapdays()

Returns the number of leap years in the range [y1, y2).

import calendar

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

Day of the Week

weekday()

Returns the day of the week (0 is Monday) for year, month, day.

import calendar

day = calendar.weekday(2023, 10, 31)
print(day) # Output: 1 (Tuesday)

Day Names

You can access day and month names.

import calendar

print(list(calendar.day_name))
# Output: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

print(list(calendar.month_name))
# Output: ['', 'January', 'February', ...]

programming/python/python