Python的calendar模块可生成日历并处理日期操作。1. 用calendar.month(2023,9)输出2023年9月美观日历;2. calendar.calendar(2023)显示全年日历;3. calendar.monthcalendar(2023,9)返回二维列表,每行代表一周,0表示非当月天数;4. isleap()判断闰年,monthrange()获取每月天数与首日星期,setfirstweekday()设置周起始日。

可以,Python 3 中的 calendar 模块专门用于生成日历。它能以多种格式输出年、月的日历,还能处理与日期相关的操作,比如判断闰年、获取某月第一天是星期几等。
1. 输出某月的日历
使用 calendar.month(year, month) 可直接打印指定月份的美观日历:
import calendar print(calendar.month(2023, 9))
输出结果类似:
September 2023
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
2. 输出整年的日历
用 calendar.calendar(year) 生成全年12个月的日历:
立即学习“Python免费学习笔记(深入)”;
print(calendar.calendar(2023))
3. 获取日历数据(用于自定义处理)
如果需要在程序中处理日期数据,可以用 calendar.monthcalendar(year, month),它返回一个二维列表,每一行代表一周:
import calendar
cal = calendar.monthcalendar(2023, 9)
for week in cal:
print(week)
输出示例:
[0, 0, 0, 0, 0, 1, 2] [3, 4, 5, 6, 7, 8, 9] ...
其中 0 表示不属于该月的天数。
4. 其他实用功能
-
判断闰年:
calendar.isleap(2024)返回True -
获取某月有多少天:
calendar.monthrange(year, month)返回该月第一天的星期和总天数 -
设置每周起始日:默认周一开头,可用
calendar.setfirstweekday(calendar.SUNDAY)修改











