37 lines
826 B
Python
37 lines
826 B
Python
"""时间戳工具。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from datetime import datetime
|
|
from typing import Any, Optional
|
|
|
|
|
|
def now_unix() -> int:
|
|
return int(time.time())
|
|
|
|
|
|
def unix_to_iso(ts: Optional[int]) -> Optional[str]:
|
|
if ts is None:
|
|
return None
|
|
try:
|
|
return datetime.fromtimestamp(int(ts)).isoformat(timespec="seconds")
|
|
except (ValueError, OSError, OverflowError):
|
|
return None
|
|
|
|
|
|
def parse_ts_to_unix(val: Any) -> Optional[int]:
|
|
if val is None:
|
|
return None
|
|
if isinstance(val, (int, float)):
|
|
return int(val)
|
|
s = str(val).strip()
|
|
if not s:
|
|
return None
|
|
if s.isdigit():
|
|
return int(s)
|
|
try:
|
|
return int(datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp())
|
|
except ValueError:
|
|
return None
|