日期與時間
Python 內建的 `datetime` 模組可用來處理日期、時間、時間差等操作,常用類別包括:
- `datetime`:日期與時間
- `date`:只有日期
- `time`:只有時間
- `timedelta`:表示時間差
## 1. 取得當前日期與時間
```python
from datetime import datetime, date
# 取得目前日期與時間
now = datetime.now()
print(now)
# 只取得目前日期
today = date.today()
print(today)
# 格式化輸出
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)
```
可能輸出:
```text
2025-03-08 14:30:25.123456
2025-03-08
2025-03-08 14:30:25
```
常用格式符號:
| 格式 | 說明 |
|---|---|
| `%Y` | 四位數年份 |
| `%m` | 月份,01–12 |
| `%d` | 日期,01–31 |
| `%H` | 小時,00–23 |
| `%M` | 分鐘 |
| `%S` | 秒數 |
---
## 2. 取得 7 天後的日期
可以搭配 `timedelta` 進行日期加減:
```python
from datetime import date, timedelta
today = date.today()
seven_days_later = today + timedelta(days=7)
print("今天:", today)
print("7 天後:", seven_days_later)
```
也可以取得 7 天前:
```python
seven_days_ago = today - timedelta(days=7)
print("7 天前:", seven_days_ago)
```
`timedelta` 也支援其他單位:
```python
from datetime import timedelta
delta = timedelta(days=2, hours=3, minutes=30)
print(delta)
```
---
## 3. 取得本月份最後一天
可以使用 `calendar.monthrange()`。它會回傳指定月份的天數:
```python
from datetime import date
import calendar
today = date.today()
year = today.year
month = today.month
last_day = calendar.monthrange(year, month)[1]
last_date = date(year, month, last_day)
print("本月份最後一天:", last_date)
```
例如目前是 2025 年 3 月,輸出:
```text
本月份最後一天: 2025-03-31
```
`calendar.monthrange(year, month)` 的回傳值如下:
```python
(第一天是星期幾, 該月份總天數)
```
例如:
```python
import calendar
print(calendar.monthrange(2025, 2))
```
可能輸出:
```text
(5, 28)
```
其中 `28` 就是 2025 年 2 月的最後一天日期。
## 綜合範例
```python
from datetime import datetime, date, timedelta
import calendar
# 當前日期與時間
now = datetime.now()
print("現在時間:", now.strftime("%Y-%m-%d %H:%M:%S"))
# 7 天後
seven_days_later = date.today() + timedelta(days=7)
print("7 天後:", seven_days_later)
# 本月份最後一天
today = date.today()
last_day = calendar.monthrange(today.year, today.month)[1]
last_date = date(today.year, today.month, last_day)
print("本月份最後一天:", last_date)
```
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫