Files
awoooi/apps/api/src/utils/timezone.py
OG T cd37befbe6
Some checks failed
CD Pipeline / build-and-deploy (push) Has been cancelled
Type Sync Check / check-type-sync (push) Successful in 59s
fix(models): 全面替換 datetime.UTC → timezone.utc 相容 Python 3.10
terminal.py, incident.py, utils/timezone.py 同樣問題。
CI runner Python 3.10 無 UTC 常數,導致所有模型靜默 import 失敗。

# 2026-04-06 ogt: 完整修復,不再有漏網之魚

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 12:40:27 +08:00

71 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
AWOOOI - 時區工具
==================
統一使用 Asia/Taipei (UTC+8) 時區
🔴 HARD RULE: 全系統使用台北時區,禁止 UTC
"""
from datetime import datetime, timedelta, timezone
# 台北時區 (UTC+8)
TAIPEI_TZ = timezone(timedelta(hours=8))
def now_taipei() -> datetime:
"""
取得台北時區當前時間
Returns:
datetime: 帶有 +08:00 時區資訊的 datetime
Example:
>>> now_taipei().isoformat()
'2026-03-25T02:08:04+08:00'
"""
return datetime.now(TAIPEI_TZ)
def to_taipei(dt: datetime) -> datetime:
"""
將 datetime 轉換為台北時區
Args:
dt: 任何 datetime (可能是 UTC 或 naive)
Returns:
datetime: 台北時區的 datetime
"""
if dt.tzinfo is None:
# naive datetime假設是 UTC
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(TAIPEI_TZ)
def format_taipei(dt: datetime | None = None, fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
"""
格式化為台北時區字串
Args:
dt: datetime (預設為當前時間)
fmt: strftime 格式
Returns:
str: 格式化的時間字串
"""
if dt is None:
dt = now_taipei()
else:
dt = to_taipei(dt)
return dt.strftime(fmt)
def now_taipei_iso() -> str:
"""
取得 ISO 格式的台北時區時間
Returns:
str: ISO 格式,例如 '2026-03-25T02:08:04+08:00'
"""
return now_taipei().isoformat()