#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 時區工具函數 Author: PANJIT IT Team Created: 2025-09-02 """ from datetime import datetime, timezone, timedelta from typing import Optional # 台灣時區 UTC+8 TAIWAN_TZ = timezone(timedelta(hours=8)) def now_taiwan() -> datetime: """取得當前台灣時間(UTC+8)""" return datetime.now(TAIWAN_TZ) def now_utc() -> datetime: """取得當前 UTC 時間""" return datetime.now(timezone.utc) def to_taiwan_time(dt: datetime) -> datetime: """將 datetime 轉換為台灣時間 Args: dt: datetime 物件(可能是 naive 或 aware) Returns: 台灣時區的 datetime 物件 """ if dt is None: return None # 如果是 naive datetime,假設為 UTC if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) # 轉換為台灣時區 return dt.astimezone(TAIWAN_TZ) def to_utc_time(dt: datetime) -> datetime: """將 datetime 轉換為 UTC 時間 Args: dt: datetime 物件(可能是 naive 或 aware) Returns: UTC 時區的 datetime 物件 """ if dt is None: return None # 如果是 naive datetime,假設為台灣時間 if dt.tzinfo is None: dt = dt.replace(tzinfo=TAIWAN_TZ) # 轉換為 UTC return dt.astimezone(timezone.utc) def format_taiwan_time(dt: datetime, format_str: str = "%Y-%m-%d %H:%M:%S") -> str: """格式化台灣時間為字符串 Args: dt: datetime 物件 format_str: 格式化字符串 Returns: 格式化後的時間字符串 """ if dt is None: return "" taiwan_dt = to_taiwan_time(dt) return taiwan_dt.strftime(format_str) def parse_taiwan_time(time_str: str, format_str: str = "%Y-%m-%d %H:%M:%S") -> datetime: """解析台灣時間字符串為 datetime Args: time_str: 時間字符串 format_str: 解析格式 Returns: 台灣時區的 datetime 物件 """ naive_dt = datetime.strptime(time_str, format_str) return naive_dt.replace(tzinfo=TAIWAN_TZ) # 為了向後兼容,提供替代 datetime.utcnow() 的函數 def utcnow() -> datetime: """取得當前 UTC 時間(替代 datetime.utcnow()) 注意:新代碼建議使用 now_taiwan() 或 now_utc() """ return now_utc().replace(tzinfo=None) # 返回 naive UTC datetime 以保持兼容性