如何在 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
廣告