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

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • What is PyCharm? Uses, History, and Step-by-Step Installation Guide

    What is PyCharm? PyCharm is a popular Integrated Development Environment (IDE) specifically designed for Python development. It is developed by JetBrains and is widely used by Python developers for its powerful features, ease of use, and support for various Python frameworks and tools. PyCharm is available in two editions: Uses of PyCharm PyCharm is a…

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • Python Primitive Data Types & Functions: Explained with Examples

    1. Primitive Data Types Primitive data types are the most basic building blocks in Python. They represent simple, single values and are immutable (cannot be modified after creation). Key Primitive Data Types Type Description Example int Whole numbers (positive/negative) x = 10 float Decimal numbers y = 3.14 bool Boolean (True/False) is_valid = True str…

Leave a Reply

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