SoFunction
Updated on 2025-04-14

Detailed explanation of the use of the calendar library that comes with Python

In Python development, we often need to deal with dates and times. AlthoughdatetimeLibrary is the most commonly used choice, but in fact, the Python standard librarycalendarModules are also a powerful tool, especially suitable for handling calendar-related calculations and presentations.

Start with a real scene

Suppose you are developing a conference room reservation system, you need:

  • Show monthly view
  • Calculate working days
  • Handle holiday logic

Let's see how to use itcalendarto solve these problems gracefully.

Basic usage: Generate calendar

import calendar

# Create a calendar objectc = ()

# Generate a calendar for January 2024print((2024, 1))

This generates a formatted calendar:

    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

Advanced App: Custom Work Calendar

import calendar
from datetime import date, timedelta

class BusinessCalendar():
    def __init__(self, holidays=None):
        super().__init__()
         = holidays or set()
    
    def get_working_days(self, year, month):
        """Get the working day of the specified month"""
        working_days = []
        for day in self.itermonthdays2(year, month):
            # day[0] is the date, day[1] is the week (0-6, 0 is Monday)            if day[0] > 0:  # Exclude filling dates                current_date = date(year, month, day[0])
                # Skip on weekends or holidays                if day[1] < 5 and current_date not in :
                    working_days.append(current_date)
        return working_days

#User Exampleholidays = {date(2024, 1, 1), date(2024, 2, 10)}  # New Year's Day and Spring Festivalbc = BusinessCalendar(holidays)
working_days = bc.get_working_days(2024, 1)
print(f"2024Year1Number of monthly working days:{len(working_days)}")

Practical Tips: Judge a specific date

import calendar
from datetime import date, timedelta

def is_last_day_of_month(date_obj):
    """Judge whether it is the last day of the month"""
    return date_obj.day == (date_obj.year, date_obj.month)[1]

def get_next_weekday(date_obj, weekday):
    """Get the date of the next specified week"""
    days_ahead = weekday - date_obj.weekday()
    if days_ahead <= 0:
        days_ahead += 7
    return date_obj + timedelta(days=days_ahead)

#User Exampletoday = ()
print(f"Is it the end of the month today:{is_last_day_of_month(today)}")
next_monday = get_next_weekday(today, )
print(f"Next Monday is:{next_monday}")

Calendar Magic in the Command Line: Calendar Command Line Tool

Python is a "scripting language", naturallycalendarModules can not only be used in code, but also can be used directly on the command line as tools.

Basic usage

The easiest way to use it is to directly display the calendar of the year:

python -m calendar
...
      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6                   1  2  3                         1
 7  8  9 10 11 12 13       4  5  6  7  8  9 10       2  3  4  5  6  7  8
14 15 16 17 18 19 20      11 12 13 14 15 16 17       9 10 11 12 13 14 15
21 22 23 24 25 26 27      18 19 20 21 22 23 24      16 17 18 19 20 21 22
28 29 30 31               25 26 27 28 29 30         23 24 25 26 27 28 29
                                                    30 31

Displays the calendar for the specified year:

python -m calendar 2024

Displays the calendar for the specified year and month:

python -m calendar 2024 1  # Show January 2024
    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

Practical Tips

Save the calendar to a file:

python -m calendar 2024 > calendar_2024.txt

Use with other commands:

# Show specific month and highlight today's date (using grep)python -m calendar | grep -C 6 "$(date '+%-d')"

Tips

In Unix/Linux systems, you can create alias for commonly used calendar commands:

alias mycal='python -m calendar'

CooperategrepUse it to quickly find specific dates:

python -m calendar 2024 | grep -A 7 "January"  # Show January 2024

The advantage of command-line tools is fast viewing and simple date calculations, which are especially suitable for use in the following scenarios:

  • Quickly view date schedules
  • Do date checking in terminal
  • Calendar functionality is required when writing shell scripts
  • Need to generate a calendar report in plain text format

Use via command linecalendarModule, we can quickly obtain the required calendar information, which is a very practical tool for developers who often use the command line.

Practical advice

  • usecalendarPriority to inheritance when dealing with calendar presentation and calculationsCalendarClasses to extend functionality
  • For repetitive date calculations, you can create custom calendar classes
  • CombineddatetimeandcalendarUsed to handle more complex time computing scenarios

Summarize

Python'scalendarThe modules look simple, but they are actually very practical. Not only does it generate a beautiful calendar, it also helps us deal with various date calculation problems. Especially when dealing with business scenarios such as working days and holidays,calendarThe advantages of modules are very obvious.

It is recommended that you try to use it more in actual developmentcalendarModules, it can make your code more Pythonic and easier to maintain.

This is the article about the detailed explanation of the use of the calendar library that comes with Python. For more related Python calendar content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!