杰瑞科技汇

monthcalendar模块如何生成月历?

Of course! The calendar.monthcalendar() function is a very useful tool in Python's built-in calendar module. It's designed to give you a structured representation of a month's calendar, which is perfect for generating calendars for display in applications, reports, or web pages.

monthcalendar模块如何生成月历?-图1
(图片来源网络,侵删)

Here's a complete guide, from the basics to more advanced usage.

What is calendar.monthcalendar()?

Its primary job is to take a year and a month and return a list of weeks. Each week is itself a list of days.

The key features are:

  • A week is a list of 7 integers. Each integer represents a day of the month.
  • Days from the previous or next month are represented by 0. This is incredibly helpful for knowing where the month starts and ends within the standard Monday-Sunday (or Sunday-Saturday) grid.
  • The first week of the list always contains the 1st of the month.

The Basic Syntax

import calendar
calendar.monthcalendar(year, month)

Parameters:

monthcalendar模块如何生成月历?-图2
(图片来源网络,侵删)
  • year (int): The year for the calendar (e.g., 2025).
  • month (int): The month for the calendar (1-12).

Return Value:

  • A list of week lists. Each week list contains 7 integers representing the days.

Simple Example

Let's get the calendar for October 2025.

import calendar
# Get the calendar for October 2025
oct_2025 = calendar.monthcalendar(2025, 10)
# Print the result
print(oct_2025)

Output:

[[0, 0, 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, 30],
 [31, 0, 0, 0, 0, 0, 0]]

Let's break down this output:

monthcalendar模块如何生成月历?-图3
(图片来源网络,侵删)
  • The result is a list of 6 weeks (lists).
  • Week 1: [0, 0, 0, 0, 0, 1, 2]
    • October 1st, 2025 was a Sunday. In the default US locale, weeks start on Sunday (index 0).
    • The first 5 days of this week (Monday-Friday) are from the previous month (September), so they are 0.
    • The 6th and 7th elements (Saturday and Sunday) are the 1st and 2nd of October.
  • Week 2-5: These are the full weeks within October.
  • Week 6: [31, 0, 0, 0, 0, 0, 0]
    • October 31st was a Tuesday.
    • The rest of the days in this week (Wednesday-Sunday) are from the next month (November), so they are 0.

Advanced Usage and Customization

a) Changing the First Day of the Week

By default, the first day of the week is calendar.SUNDAY (which is 6). You can change this to calendar.MONDAY (which is 0) using the calendar.setfirstweekday() function.

import calendar
# Set Monday as the first day of the week
calendar.setfirstweekday(calendar.MONDAY)
# Get the calendar for October 2025 again
oct_2025_mon = calendar.monthcalendar(2025, 10)
print(oct_2025_mon)

Output (Notice the difference!):

[[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, 30, 31, 0, 0]]
  • Now, the first week starts on Monday (index 0). The first day of October, 2025 (a Sunday), is now at the end of the first week as a 0.

b) Formatting for Display

The raw list of numbers isn't very user-friendly. Let's format it into a nice, readable calendar. This is a very common use case.

import calendar
def print_calendar(year, month):
    """
    Prints a nicely formatted calendar for a given year and month.
    """
    # Get the calendar data
    cal = calendar.monthcalendar(year, month)
    # Get the month and year names
    month_name = calendar.month_name[month]
    header = f"{month_name} {year}".center(20)
    print(header)
    print("-" * 20)
    # Print day headers (e.g., Mo, Tu, We...)
    week_header = " Mo Tu We Th Fr Sa Su"
    print(week_header)
    print("-" * 20)
    # Print each week
    for week in cal:
        # Convert 0s to spaces for display
        week_str = [f"{day:2d}" if day != 0 else "  " for day in week]
        # Join the list into a string
        print(" ".join(week_str))
# --- Example Usage ---
print("Calendar for October 2025 (starts on Monday):")
print_calendar(2025, 10)

Output:

Calendar for October 2025 (starts on Monday):
      October 2025       
--------------------
 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

c) Finding Specific Days

The 0 values are perfect for filtering out days that don't belong to the target month.

Let's find all the Mondays in October 2025.

import calendar
year = 2025
month = 10
mondays = []
# Get the calendar data
cal = calendar.monthcalendar(year, month)
# Monday is the first day of the week (index 0)
for week in cal:
    if week[0] != 0: # Check if it's not a day from the previous month
        mondays.append(week[0])
print(f"Mondays in October {year}:")
print(mondays)

Output:

Mondays in October 2025:
[2, 9, 16, 23, 30]

Comparison with calendar.month()

It's helpful to know the difference between monthcalendar() and calendar.month().

Feature calendar.monthcalendar(year, month) calendar.month(year, month)
Output Type List of lists of integers Single string
Purpose For programmatic processing, data extraction, and building custom UIs. For direct printing to the console.
Example [[0, 0, 0, 0, 0, 1, 2], ...] " October 2025\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5 6 7\n..."

Use monthcalendar() when you need to work with the calendar data as data. Use month() when you just want a quick, formatted printout.


Summary

Function Best For Key Feature
calendar.monthcalendar() Data processing, building UIs, custom formatting Returns a list of lists. Days from other months are 0.
calendar.month() Quick console printing Returns a pre-formatted string.

calendar.monthcalendar() is a powerful and flexible function that forms the backbone of many calendar-related applications in Python. Understanding how it handles the 0 values is the key to using it effectively.

分享:
扫描分享到社交APP
上一篇
下一篇