在 Python 开发中,我们经常需要处理日期和时间。虽然 datetime
库是最常用的选择,但其实 Python 标准库中的 calendar
模块也是一个强大的工具,特别适合处理日历相关的计算和展示。
从一个真实场景开始
假设你正在开发一个会议室预订系统,需要:
- 展示月度视图
- 计算工作日
- 处理节假日逻辑
让我们看看如何用 calendar
来优雅地解决这些问题。
基础用法:生成日历
import calendar
# 创建日历对象
c = calendar.TextCalendar()
# 生成 2024 年 1 月的日历
print(c.formatmonth(2024, 1))
这会生成一个格式化的月历:
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
高级应用:自定义工作日历
import calendar
from datetime import date, timedelta
class BusinessCalendar(calendar.Calendar):
def __init__(self, holidays=None):
super().__init__()
self.holidays = holidays or set()
def get_working_days(self, year, month):
"""获取指定月份的工作日"""
working_days = []
for day in self.itermonthdays2(year, month):
# day[0] 是日期,day[1] 是星期(0-6,0是周一)
if day[