Python Calendar Module
Python Calendar Module
The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations.
Importing the Module
python
import calendar
Key Methods in the Calendar Module
1. calendar.month(year, month, w=2, l=1)
Returns a multiline string with a calendar for the specified month.
Parameters:
year: Year (e.g., 2024)month: Month (1-12)w: Width of date columns (default: 2)l: Number of lines per week (default: 1)
python
import calendar # Display calendar for January 2024 print(calendar.month(2024, 1))
Output:
text
January 2024 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 31
2. calendar.calendar(year, w=2, l=1, c=6, m=3)
Returns a multiline string with a calendar for the entire year.
Parameters:
year: Yearw: Width of date columnsl: Number of lines per weekc: Number of spaces between monthsm: Number of months per row
python
import calendar # Display entire year 2024 (first 3 months) print(calendar.calendar(2024, m=3)[:1000]) # Showing first 1000 characters
3. calendar.isleap(year)
Returns True if the year is a leap year, False otherwise.
python
import calendar print(calendar.isleap(2024)) # True print(calendar.isleap(2023)) # False print(calendar.isleap(2000)) # True print(calendar.isleap(1900)) # False
4. calendar.leapdays(y1, y2)
Returns the number of leap years between years y1 and y2 (exclusive).
python
import calendar print(calendar.leapdays(2000, 2024)) # 6 leap years (2000, 2004, 2008, 2012, 2016, 2020)
5. calendar.weekday(year, month, day)
Returns the day of the week as an integer (0=Monday, 6=Sunday).
python
import calendar
# Check what day January 1, 2024 falls on
day_index = calendar.weekday(2024, 1, 1)
print(f"Day index: {day_index}") # 0 (Monday)
# Convert to day name
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(f"January 1, 2024 was a {days[day_index]}")
6. calendar.monthrange(year, month)
Returns a tuple (weekday_of_first_day, number_of_days) for the specified month.
python
import calendar
# Get information about February 2024
first_day, num_days = calendar.monthrange(2024, 2)
print(f"First day index: {first_day}") # 3 (Thursday)
print(f"Number of days: {num_days}") # 29 (leap year)
7. calendar.monthcalendar(year, month)
Returns a matrix representing a month’s calendar.
python
import calendar
# Get February 2024 as a matrix
feb_2024 = calendar.monthcalendar(2024, 2)
print("February 2024 matrix:")
for week in feb_2024:
print(week)
Output:
text
February 2024 matrix: [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, 0, 0, 0]
8. calendar.day_name and calendar.day_abbr
Lists of full and abbreviated day names.
python
import calendar
print("Full day names:")
for day in calendar.day_name:
print(day)
print("\nAbbreviated day names:")
for day in calendar.day_abbr:
print(day)
Output:
text
Full day names: Monday Tuesday Wednesday Thursday Friday Saturday Sunday Abbreviated day names: Mon Tue Wed Thu Fri Sat Sun
9. calendar.month_name and calendar.month_abbr
Lists of full and abbreviated month names.
python
import calendar
print("Full month names:")
for i, month in enumerate(calendar.month_name):
print(f"{i}: {month}")
print("\nAbbreviated month names:")
for i, month in enumerate(calendar.month_abbr):
print(f"{i}: {month}")
Practical Examples
Example 1: Check if a date is a weekend
python
import calendar
def is_weekend(year, month, day):
day_index = calendar.weekday(year, month, day)
return day_index >= 5 # 5=Saturday, 6=Sunday
print(is_weekend(2024, 1, 6)) # True (Saturday)
print(is_weekend(2024, 1, 7)) # True (Sunday)
print(is_weekend(2024, 1, 8)) # False (Monday)
Example 2: Get all Fridays in a month
python
import calendar
def get_fridays(year, month):
fridays = []
cal = calendar.monthcalendar(year, month)
for week in cal:
if week[4] != 0: # Friday is index 4
fridays.append(week[4])
return fridays
fridays_jan_2024 = get_fridays(2024, 1)
print(f"Fridays in January 2024: {fridays_jan_2024}")
Example 3: Custom calendar formatting
python
import calendar
def custom_calendar(year, month):
# Set first weekday to Sunday (0=Monday, 6=Sunday by default)
calendar.setfirstweekday(calendar.SUNDAY)
# Create calendar with custom width
cal_text = calendar.month(year, month, w=4)
return cal_text
print(custom_calendar(2024, 12))
Example 4: Count working days in a month
python
import calendar
def count_working_days(year, month):
first_day, num_days = calendar.monthrange(year, month)
working_days = 0
for day in range(1, num_days + 1):
weekday = calendar.weekday(year, month, day)
if weekday < 5: # Monday to Friday
working_days += 1
return working_days
work_days_jan = count_working_days(2024, 1)
print(f"Working days in January 2024: {work_days_jan}")
Setting the First Day of the Week
By default, Monday is the first day of the week. You can change this:
python
import calendar
# Set Sunday as first day of week
calendar.setfirstweekday(calendar.SUNDAY)
# Or use integer (6 for Sunday)
calendar.setfirstweekday(6)
# Get current first weekday
print(f"First weekday: {calendar.firstweekday()}") # Returns 6 for Sunday
The calendar module is particularly useful for applications that need to generate calendar views, calculate dates, or work with scheduling systems.