Files
jwxt/app/time_utils.py

55 lines
1.5 KiB
Python
Raw Permalink 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.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
统一时间工具模块 - 使用北京时间(Asia/Shanghai)存储为 ISO 格式
"""
from datetime import datetime, timezone, timedelta
# 北京时区(兼容 Python 3.8 及以下)
BJ_TZ = timezone(timedelta(hours=8))
def now() -> datetime:
"""返回当前北京时间(带时区信息的 aware datetime)"""
return datetime.now(BJ_TZ)
def utc_now() -> datetime:
"""返回当前 UTC 时间(兼容旧代码)"""
return datetime.now(timezone.utc)
def today() -> datetime:
"""返回今天的日期(北京时间,零点)"""
return datetime.now(BJ_TZ).replace(hour=0, minute=0, second=0, microsecond=0)
def to_iso(dt: datetime | None) -> str | None:
"""将 datetime 转为 ISO 格式字符串(北京时间)"""
if dt is None:
return None
if dt.tzinfo is None:
# naive datetime,视为北京时间
dt = dt.replace(tzinfo=BJ_TZ)
return dt.isoformat()
def from_iso(iso_str: str | None) -> datetime | None:
"""从 ISO 格式字符串解析为北京时间(带时区)"""
if not iso_str:
return None
dt = datetime.fromisoformat(iso_str.replace('Z', '+00:00'))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=BJ_TZ)
return dt
def timestamp() -> float:
"""返回当前时间戳(秒)"""
return now().timestamp()
def timestamp_ms() -> int:
"""返回当前时间戳(毫秒)"""
return int(now().timestamp() * 1000)