Calendar 模块是 Python 内置的日历处理模块,提供了多种与日历相关的功能。
基本功能
1. 检查闰年
python
# 判断某年是否为闰年
print(calendar.isleap(2024)) # True
print(calendar.isleap(2023)) # False
2. 获取两个年份之间的闰年数量
python
# 获取从2000到2024年之间的闰年数量
leap_count = calendar.leapdays(2000, 2025)
print(f"2000-2024年之间的闰年数量: {leap_count}") # 7
3. 获取星期几
python
# 返回指定日期的星期几(周一是0,周日是6)
weekday = calendar.weekday(2024, 1, 15)
print(f"2024年1月15日是星期: {weekday}") # 0 (星期一)
# 或者使用更友好的方式
days = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
print(f"2024年1月15日是: {days[weekday]}")
日历显示
1. 文本日历
python
# 生成一个月的文本日历
january_2024 = calendar.month(2024, 1)
print(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
# 生成全年的文本日历
year_calendar = calendar.calendar(2024)
print(year_calendar) # 这会打印2024年全年的日历
2. HTML 日历
python
# 生成HTML格式的月历
html_month = calendar.HTMLCalendar().formatmonth(2024, 1)
print(html_month)
# 生成HTML格式的年历
html_year = calendar.HTMLCalendar().formatyear(2024)
print(html_year)
3. 自定义日历显示
python
# 创建自定义日历对象
cal = calendar.TextCalendar(calendar.SUNDAY) # 设置周日为一周的第一天
# 生成以周日开始的月历
sunday_first = cal.formatmonth(2024, 1)
print(sunday_first)
日期计算
1. 获取月份天数矩阵
python
# 获取一个月的日期矩阵(周为行,日为列,不在该月的日期为0)
month_days = calendar.monthcalendar(2024, 1)
print("2024年1月的日期矩阵:")
for week in month_days:
print(week)
# 输出:
# [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]
2. 获取月份范围
python
# 获取月份的第一天和天数
first_weekday, month_days_count = calendar.monthrange(2024, 2)
print(f"2024年2月第一天是星期: {first_weekday}") # 3 (星期四)
print(f"2024年2月有 {month_days_count} 天") # 29
实用功能
1. 自定义日历类
python
class CustomCalendar(calendar.TextCalendar):
def __init__(self, firstweekday=0):
super().__init__(firstweekday)
def formatday(self, day, weekday, width):
"""重写日期格式化方法"""
if day == 0:
return ' ' * width
elif day == 15: # 特殊标记某一天
return f'[{day:2d}]'
else:
return super().formatday(day, weekday, width)
custom_cal = CustomCalendar()
custom_month = custom_cal.formatmonth(2024, 1)
print(custom_month)
2. 迭代器功能
python
# 按周迭代月份中的日期
cal = calendar.Calendar()
print("2024年1月的周迭代:")
for week in cal.monthdatescalendar(2024, 1):
print(week)
# 按天迭代月份中的日期
print("\n2024年1月的天迭代:")
for day in cal.itermonthdays(2024, 1):
print(day, end=' ')
print()
# 迭代月份中的日期和星期
print("\n2024年1月的日期和星期:")
for day, weekday in cal.itermonthdays2(2024, 1):
if day != 0:
print(f"日期: {day}, 星期: {weekday}")
完整示例
示例1:创建个人日程管理器
python
import calendar
from datetime import date
class PersonalCalendar:
def __init__(self, year):
self.year = year
self.events = {}
self.cal = calendar.Calendar()
def add_event(self, month, day, event):
"""添加事件"""
key = (month, day)
if key not in self.events:
self.events[key] = []
self.events[key].append(event)
def display_month_with_events(self, month):
"""显示带事件的月份日历"""
cal = calendar.TextCalendar()
month_str = cal.formatmonth(self.year, month)
print(f"\n{self.year}年{month}月日程:")
print(month_str)
# 显示事件
print("本月事件:")
for (m, day), events in self.events.items():
if m == month:
print(f" {day}日: {', '.join(events)}")
def get_busy_days(self, month):
"""获取有事件的日期"""
busy_days = []
for (m, day), events in self.events.items():
if m == month and events:
busy_days.append(day)
return sorted(busy_days)
# 使用示例
my_calendar = PersonalCalendar(2024)
# 添加事件
my_calendar.add_event(1, 15, "团队会议")
my_calendar.add_event(1, 20, "医生预约")
my_calendar.add_event(1, 15, "项目截止")
my_calendar.add_event(2, 14, "情人节")
# 显示日历
my_calendar.display_month_with_events(1)
# 获取繁忙日期
busy_days = my_calendar.get_busy_days(1)
print(f"1月繁忙日期: {busy_days}")
示例2:节假日日历
python
import calendar
class HolidayCalendar:
def __init__(self, year, country='CN'):
self.year = year
self.country = country
self.holidays = self._get_holidays()
def _get_holidays(self):
"""定义节假日(这里以中国节假日为例)"""
holidays = {
(1, 1): "元旦",
(2, 10): "春节",
(2, 11): "春节",
(2, 12): "春节",
(4, 4): "清明节",
(5, 1): "劳动节",
(6, 14): "端午节",
(9, 21): "中秋节",
(10, 1): "国庆节",
(10, 2): "国庆节",
(10, 3): "国庆节",
}
return holidays
def display_holiday_calendar(self, month):
"""显示带节假日的日历"""
cal = calendar.TextCalendar()
month_days = cal.monthdayscalendar(self.year, month)
print(f"\n{self.year}年{month}月节假日日历:")
print("一 二 三 四 五 六 日")
print("-" * 20)
for week in month_days:
week_str = ""
for day in week:
if day == 0:
week_str += " "
else:
holiday = self.holidays.get((month, day))
if holiday:
week_str += f"*{day:2d}"
else:
week_str += f" {day:2d}"
print(week_str)
# 显示节假日说明
print("\n节假日说明:")
for (m, day), holiday in self.holidays.items():
if m == month:
print(f" {day}日: {holiday}")
# 使用示例
holiday_cal = HolidayCalendar(2024)
holiday_cal.display_holiday_calendar(1)
holiday_cal.display_holiday_calendar(2)
示例3:工作日计算器
python
import calendar
from datetime import date, timedelta
class WorkdayCalculator:
def __init__(self, year):
self.year = year
self.cal = calendar.Calendar()
self.workdays = 0
self.weekends = 0
def calculate_workdays(self, month=None):
"""计算工作日和周末天数"""
if month:
months = [month]
else:
months = range(1, 13)
total_workdays = 0
total_weekends = 0
for month in months:
month_workdays = 0
month_weekends = 0
for day, weekday in self.cal.itermonthdays2(self.year, month):
if day != 0: # 排除不在该月的日期
if weekday in [5, 6]: # 周六、周日
month_weekends += 1
else:
month_workdays += 1
total_workdays += month_workdays
total_weekends += month_weekends
if not month: # 如果指定了月份,显示该月统计
print(f"{self.year}年{month}月: 工作日{month_workdays}天, 周末{month_weekends}天")
return total_workdays, total_weekends
# 使用示例
calculator = WorkdayCalculator(2024)
workdays, weekends = calculator.calculate_workdays()
print(f"\n{2024}年统计:")
print(f"总工作日: {workdays}天")
print(f"总周末: {weekends}天")
print(f"总天数: {workdays + weekends}天")
# 计算特定月份
jan_workdays, jan_weekends = calculator.calculate_workdays(1)
print(f"\n2024年1月: 工作日{jan_workdays}天, 周末{jan_weekends}天")
总结
Python 的 calendar 模块提供了丰富的日历处理功能:
-
基本功能: 闰年判断、星期计算、日期验证
-
日历显示: 文本日历、HTML日历、自定义格式
-
日期计算: 月份范围、日期矩阵、迭代器
-
扩展应用: 日程管理、节假日处理、工作日计算