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 模块专门用于生成日历。它能以多种格式输出年、月的日历,还能处理与日期相关的操作,比如判断闰年、获取某月第一天是星期几等。
使用 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
用 calendar.calendar(year) 生成全年12个月的日历:
立即学习“Python免费学习笔记(深入)”;
print(calendar.calendar(2023))
如果需要在程序中处理日期数据,可以用 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 表示不属于该月的天数。
calendar.isleap(2024) 返回 True
calendar.monthrange(year, month) 返回该月第一天的星期和总天数calendar.setfirstweekday(calendar.SUNDAY) 修改以上就是calendar可以在python3时间中生成日历吗?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号