Python Calendar Module

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

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

  • How to create Class

    πŸŸ₯ Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: πŸ“ Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

  • 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}”,…

  • What is Quantum Computing? A Beginner’s Guide to the Future of Technology

    What is Quantum Computing? Quantum computing is a revolutionary approach to computation that leverages the principles of quantum mechanics to perform complex calculations far more efficiently than classical computers. Unlike classical computers, which use bits (0s and 1s) as the smallest unit of information, quantum computers use quantum bits (qubits), which can exist in multiple…

  • start(), end(), and span()

    Python re start(), end(), and span() Methods Explained These methods are used with match objects to get the positional information of where a pattern was found in the original string. They work on the result of re.search(), re.match(), or re.finditer(). Methods Overview: Example 1: Basic Position Tracking python import re text = “The quick brown fox jumps over the lazy…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

Leave a Reply

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