Python 日历模块示例

⚡ 智能摘要

日历模块 Python 使用 TextCalendar 和 HTMLCalendar 类生成文本和 HTML 日历。它根据日、月、年进行日期计算,并允许您自定义任何月份的起始星期几。

  • 🔘 两种日历类型: TextCalendar 和 HTMLCalendar 类可以生成所选月份或年份的纯文本和可用于 Web 的日历。
  • ☑️ 第一个工作日: 诸如 calendar.SUNDAY 之类的常量和 setfirstweekday() 方法会改变每周的开始日期。
  • 重复天数: itermonthdays() 方法遍历一个月并标记重叠部分。ping 相邻月份的日期设为零。
  • 🧪 辅助函数: isleap()、weekday() 和 monthrange() 等函数无需任何额外的库即可回答常见的日期问题。
  • 🛠️ 标准库: 日历模块随附 Python因此,导入和使用前无需安装。
  • 🤖 人工智能工作流程: 机器学习管道提取日历特征,例如星期几和闰年标志,用于时间序列预测。

Python 日历模块

日历模块 Python 它包含一个日历类,可以根据日期、月份和年份计算各种任务。除此之外, 文本日历HTML日历 课程 Python 允许您编辑日历并根据您的需要使用它。让我们看看我们能用它做些什么。 Python 日历。

什么是日历模块? Python?

日历模块 是的一部分 Python 它是标准库的一部分,无需安装即可使用。它包含多个类和辅助函数,用于构建日历并回答常见的日期问题,例如某个日期是星期几或一个月有多少天。

该模块提供五个主要类:

  • 日历 是一个基类,它提供其他日历所依赖的数据。
  • 文本日历 生成一个月或一整年的纯文本日历。
  • HTML日历 将日历生成为网页上的 HTML 表格。
  • 本地化文本日历 是一个文本日历,使用所选地区的日期和月份名称。
  • 本地化HTML日历 是遵循所选区域设置的 HTML 等效项。

默认情况下,日历周从……开始。 Monday遵循欧洲惯例。您可以使用常量(例如 calendar.SUNDAY)更改第一天,如下例所示。

如何打印文本日历 Python

步骤1) 运行代码。

打印文本日历 Python

  • Code 第 1 行:我们从“import calendar”开始,这将导入此模块的所有类。
  • Code 第 3 行:c= calendar.TextCalendar(calendar.SUNDAY) 告诉解释器创建一个文本日历。每月的第一天是星期日。 Python您可以根据自己的喜好设置日历格式,并更改每月的起始日期。
  • Code 第 4 行:str= c.formatmonth(2025,1) 创建一个 2025 年 1 月的日历。
  • Code 第 5 行:print str 将打印输出。

让我们快速将日期从星期日改为星期四,并检查输出结果。

更改第一个工作日 Python 日历

如何打印 HTML 日历 Python

步骤2) 您还可以将日历打印为 HTML 格式。此功能对想要更改日历外观的开发人员非常有用。

打印 HTML 日历 Python

如何循环遍历一个月中的每一天

步骤3) 使用 c.itermonthdays (2025,4) 可以计算一个月中的天数;它将获取该月的总天数。

循环遍历一个月中的每一天 Python

  • 当你执行代码来获取特定月份(例如“四月”)的总天数时,你会在输出中得到 30 天,但你也会在这些天数的开头和结尾看到一些零。
  • 输出结果中的零表示该日期与星期几重叠。ping 月份,这意味着它不属于那个月份。
  • 输出中出现这些零是因为你的代码中指定了日期(星期四)。所以当你调用函数“c.itermonthdays”时,它会从星期四开始计数,而你的星期四可能并非4月1日,而是3月28日或29日。因此,代码会从3月28日开始计数,直到4月1日。这些日期会被计为零,所以你会在输出中看到这些零。同样的情况也适用于月底。
  • 因此,除了 1 至 30 日之外,上个月和下个月的所有日期在输出中都显示为零。

如何从本地系统中获取月份和星期名称

步骤4) 您可以从本地系统获取数据,例如月份或星期几。

从本地系统中获取月份名称 Python

  • 此处的输出显示我们已从本地系统打印出月份名称。同样,您也可以获取星期几的名称,如下所示。
  • 输出结果取决于本地系统。如果您的本地系统设置为其他国家/地区,则会根据该国家/地区的本地设置给出输出结果。这里我们以月为单位,所以不会有太大区别,但如果是一周或一天,结果肯定会有所不同。

从本地系统中获取星期几的名称 Python

如何找到一整年的特定日期

步骤5) 您可以获取一整年内特定日期的列表。例如,每年的第一天是审计日。 Monday 一周中的某一天。假设你想知道第一天的日期。 Monday 每个月都可以使用此代码。

找到一年中特定的一天 Python

  • mycal = calendar.monthcalendar(2025, month) 创建一个月份的日历。
  • 将变量 week1 和 week2 分别设置为日历的第一周和第二周。
  • 检查第 1 周是否包含 Monday 并确定审计日期。
  • 否则,将审计日设为第一天。 Monday 第二周。
  • 输出显示第一个 Monday 属于该月。
  • 这个 Cal 对象的长度取决于该月有多少周。在我们的例子中,它是一周或两周,因为第一个 Monday 一周的最佳数据通常出现在第一周,但如果没有,我们就考虑第二周。让我们详细了解一下为什么我们也会考虑第二周。
  • 这里我们使用日历常数 Monday日历对象提供了代表星期日的常量, Monday星期二,以此类推。如果在第一周,由……代表的日期 Monday 常数不等于 0——记住,零表示属于另一个月份的日期——那么 Monday 属于本月,且审计日在第一周内。如果为 0,则为第一个 Monday 不在当月的第一周,所以一定是在第二周。
  • 在这种情况下,我们将审计日变量设置为 Monday 以第二周为准。审计日期会显示为第一周或第二周的日期。

完成: Python 日历 Code 例如:

以下是完整代码。

Python 2示例

import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print str

# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print str
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
    print i

    # The calendar can give info based on local such a names of days and months (full and abbreviated forms)
    for name in calendar.month_name:
        print name
    for day in calendar.day_name:
        print day
    # calculate days based on a rule: For instance an audit day on the second Monday of every month
    # Figure out what days that would be for each month, we can use the script as shown here
    for month in range(1, 13):
		# It retrieves a list of weeks that represent the month
        mycal = calendar.monthcalendar(2025, month)
		# The first MONDAY has to be within the first two weeks
        week1 = mycal[0]
        week2 = mycal[1]
        if week1[calendar.MONDAY] != 0:
            auditday = week1[calendar.MONDAY]
        else:
        # if the first MONDAY isn't in the first week, it must be in the second week
        	auditday = week2[calendar.MONDAY]
print "%10s %2d" % (calendar.month_name[month], auditday)

Python 3示例

import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print(str)

# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print(str)
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
    print(i)

    # The calendar can give info based on local such a names of days and months (full and abbreviated forms)
    for name in calendar.month_name:
        print(name)
    for day in calendar.day_name:
        print(day)
    # calculate days based on a rule: For instance an audit day on the second Monday of every month
    # Figure out what days that would be for each month, we can use the script as shown here
    for month in range(1, 13):
		# It retrieves a list of weeks that represent the month
        mycal = calendar.monthcalendar(2025, month)
		# The first MONDAY has to be within the first two weeks
        week1 = mycal[0]
        week2 = mycal[1]
        if week1[calendar.MONDAY] != 0:
            auditday = week1[calendar.MONDAY]
        else:
        # if the first MONDAY isn't in the first week, it must be in the second week
        	auditday = week2[calendar.MONDAY]
print("%10s %2d" % (calendar.month_name[month], auditday))

实用功能 Python 日历模块

除了上述步骤之外,日历模块还附带几个无需创建类实例即可使用的便捷函数:

  • calendar.calendar(year) 返回包含全年日历的多行字符串,而 calendar.prcal(year) 直接打印出来。
  • calendar.month(year, month) 返回单个月份的文本数据, calendar.prmonth(year, month) 打印它。
  • calendar.monthcalendar(year, month) 返回月份,以周行列表的形式表示,其中每一天都是一个整数,月份之外的日期为 0。

这些函数可以快速输出单行日历,这在脚本和交互式会话中非常方便,因为在这些情况下,您不需要对 TextCalendar 或 HTMLCalendar 类进行额外的控制。

如何查看哪一年是闰年 Python

日历模块还可以告诉你某一年是否是闰年,这很重要,因为闰年​​的二月有 29 天而不是 28 天。有两个函数可以处理这种情况:

  • calendar.isleap(year) 如果该年是闰年,则返回 True,否则返回 False。
  • calendar.leapdays(y1, y2) 返回从 y1 到 y2(不包括 y2)之间的闰年数。

例如,calendar.isleap(2024) 返回 True,而 calendar.isleap(2025) 返回 False。在验证日期、安排重复事件或计算两年之间的确切天数时,闰年检查非常有用。

常见问题

日历模块专注于生成和分析日历——包括文本、HTML、星期几数字以及闰年检查。日期时间模块则处理特定的时间戳、运算以及日期和时间的格式化。许多程序会导入这两个模块并结合使用。

调用 calendar.weekday(year, month, day)。它返回一个从 0 到 1 的整数(Monday)到 6(星期日)。将其与 calendar.day_name 结合使用,即可将该数字转换为易于理解的标签,例如: Monday 或者星期五。

使用 `calendar.monthrange(year, month)`。它返回一个元组,其中第二个值是日期计数,因此 `calendar.monthrange(2025, 2)[1]` 返回 28。第一个值是该月第一天的星期几。

使用 calendar.LocaleTextCalendar 或 calendar.LocaleHTMLCalendar 并传入一个区域设置,例如“fr_FR”。格式化后的月份将以该语言打印星期和月份名称,前提是操作系统上已安装该区域设置。

使用 `HTMLCalendar().formatmonth(2025, 1)` 生成标记,然后以写入模式打开文件并调用 `write()` 函数传入该字符串。将其保存为 `.html` 扩展名后,任何浏览器都可以显示样式化的日历。

默认情况下,一周从……开始。 Monday按照欧洲惯例,调用 calendar.setfirstweekday(calendar.SUNDAY) 或将 calendar.SUNDAY 等常量传递给 TextCalendar,即可将一周的起始日更改为其他日期。

数据管道利用日历函数从原始日期中提取星期几、周数和闰年标志等特征。这些经过处理的日历特征有助于机器学习模型捕捉时间序列预测中的每周和季节性模式。

是的。GitHub Copilot 和智能 AI 助手可以根据简短的评论编写日历模块代码片段——打印月份、检查闰年或构建 HTML 日历。 Rev查看输出结果,因为工作日索引和第一天设置很容易混淆。

总结一下这篇文章: