在日常编程中,我们经常需要处理日期、生成日历或获取某月/某年的天数等信息。Python标准库中的 calendar 模块正是为此而生!它无需额外安装,功能强大且使用简单。本教程将带你从零开始,全面了解如何使用 Python calendar库 进行各种日历和日期相关的操作。

Python的 calendar 是标准库的一部分,用于生成和操作日历。它可以输出文本格式的日历、判断闰年、获取月份天数等,非常适合需要日期处理的场景。
使用 calendar.month(year, month) 可以打印指定年份和月份的日历。
import calendar# 打印2024年7月的日历cal = calendar.month(2024, 7)print(cal)输出结果:
July 2024Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 1415 16 17 18 19 20 2122 23 24 25 26 27 2829 30 31使用 calendar.calendar(year) 可以打印一整年的日历。
import calendar# 打印2024年全年日历year_cal = calendar.calendar(2024)print(year_cal)使用 calendar.isleap(year) 可以判断某一年是否是闰年。
import calendarprint(calendar.isleap(2024)) # Trueprint(calendar.isleap(2023)) # False使用 calendar.monthrange(year, month) 返回一个元组:(该月第一天是星期几, 该月总天数)。
import calendar# 获取2024年2月的信息first_weekday, days_in_month = calendar.monthrange(2024, 2)print(f"2024年2月有 {days_in_month} 天,第一天是星期 {first_weekday}")# 输出:2024年2月有 29 天,第一天是星期 3(0=周一,6=周日)calendar.weekday(year, month, day):返回某天是星期几(0=周一,6=周日)calendar.monthcalendar(year, month):返回一个二维列表,表示该月的日历布局calendar.leapdays(y1, y2):返回 [y1, y2) 年份区间内的闰年数量你可以使用 HTMLCalendar 类生成HTML格式的日历,适合嵌入网页。
import calendar# 创建HTML日历对象html_cal = calendar.HTMLCalendar(calendar.MONDAY)# 生成2024年7月的HTML日历html_str = html_cal.formatmonth(2024, 7)# 保存到文件(可选)with open('july_2024_calendar.html', 'w', encoding='utf-8') as f: f.write(html_str)print("HTML日历已生成!")通过本教程,你已经掌握了 Python calendar库 的核心用法,包括打印日历、判断闰年、获取月份信息等。这些功能在开发任务管理、排班系统、日程提醒等应用时非常实用。记住,calendar模块 是Python标准库的一部分,无需安装第三方包,开箱即用!
无论是初学者还是有经验的开发者,掌握 Python日历操作 和 日期处理 技巧都能让你的代码更加高效和专业。快去试试吧!
本文由主机测评网于2025-12-03发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025122464.html