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: Year
  • w: Width of date columns
  • l: Number of lines per week
  • c: Number of spaces between months
  • m: 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.

Similar Posts

  • Functions Returning Functions

    Understanding Functions Returning Functions In Python, functions can return other functions, which is a powerful feature of functional programming. Basic Example python def outer(): def inner(): print(“Welcome!”) return inner # Return the inner function (without calling it) # Calling outer() returns the inner function f = outer() # f now refers to the inner function…

  • Type Conversion Functions

    Type Conversion Functions in Python πŸ”„ Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) πŸ”’ Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) πŸ’¬ Converts x…

  • Instance Variables,methods

    Instance Variables Instance variables are variables defined within a class but outside of any method. They are unique to each instance (object) of a class. This means that if you create multiple objects from the same class, each object will have its own separate copy of the instance variables. They are used to store the…

  • Exception handling & Types of Errors in Python Programming

    Exception handling in Python is a process of responding to and managing errors that occur during a program’s execution, allowing the program to continue running without crashing. These errors, known as exceptions, disrupt the normal flow of the program and can be caught and dealt with using a try…except block. How It Works The core…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”β€”the regex engine looks ahead in the string to see if the pattern inside…

Leave a Reply

Your email address will not be published. Required fields are marked *