當前位置: 妍妍網 > 辦公

Python中生成行事曆

2024-03-09辦公
在Python中生成行事曆可以透過內建的`calendar`模組來實作。下面是一些基本的例子來說明如何生成行事曆:

1. **生成特定月份的行事曆**:
```
import calendar

# 生成2024年3月的行事曆
cal = calendar.month(2024, 3)
print("March 2024 Calendar:")
print(cal)
```
上述程式碼將會打印出2024年3月份的完整行事曆。

2. **格式化輸出行事曆**:
如果你想對行事曆進行更細致的格式化控制,可以結合`formatmonth()`函式,它會返回一個二維列表,你可以自行決定如何打印這個列表:
```
import calendar

# 獲取2024年3月格式化的行事曆數據
formatted_cal = calendar.monthcalendar(2024, 3)

# 打印格式化後的行事曆
print(" March 2024")
for week in formatted_cal:
for day in week:
if day == 0: # 若day為0,則當日不屬於該月,打印空格
print(" ", end="")
else:
print("{:>4}".format(day), end=" ")
print() # 換行
```

3. **生成整年的行事曆**:
要生成整個年度的行事曆,可以使用`calendar.calendar(year, w=2, l=1)`函式,其中`w`是每周起始天數,預設是0(周一),`l`是左側周數的寬度,預設是1(只顯示周數):
```
import calendar

# 生成2024年全年的行事曆
full_year_cal = calendar.calendar(2024)

print("Full Year Calendar of 2024:")
print(full_year_cal)
```

這些函式都相當直觀且易於使用,可以根據具體需求選擇合適的函式生成所需的行事曆檢視。如果還需要進一步客製,比如將行事曆寫入Excel檔,那麽可能需要結合其他如pandas和openpyxl等庫來完成。