如何在 Python 中打印一个月的日历


Python 中,要显示日历,您需要导入calendar模块,它提供各种处理与日历相关的操作的功能,并且还包括打印文本一个月的日历

日历模块

Python 中的calendar模块提供各种函数和类来执行日期相关的操作。要在 Python 中打印日历,我们导入 calendar 模块,这将导入所有模块类。

主要功能

日历模块提供的一些功能如下

  • 日历函数:为给定月份或年份生成 HTML 或文本格式的日历。

  • 区域设置:我们可以自定义日历以匹配特定区域设置,例如一周的第一天、月份名称等。

  • 日期计算:我们还可以执行日期计算,例如查找一个月中的周数。

示例 1

下面的示例代码将打印指定年份 (yy) 和月份 (mm) 的文本日历。

# importing calendar module
import calendar

# Specifying the year and month
year = 2024
month = 8

# Creating a TextCalendar object
cal = calendar.TextCalendar(calendar.SUNDAY)

# Printing calendar for the specified month and year
print(cal.formatmonth(year, month))

输出

     August 2024
Su Mo Tu We Th Fr Sa
             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

示例 2

使用calendar.month内置函数打印日历。

# Importing the calendar module
import calendar

y = 2024

m = 9
# By using calender.month() function  

print(calendar.month(y, m))

输出

 September 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

更新于: 2024-09-23

6K+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.