grid-backtest / backend /v2 /time_sync.py
shaun07's picture
Upload folder using huggingface_hub
61ca2b1 verified
Raw History Blame Contribute Delete
5.87 kB
from __future__ import annotations
import threading
import os
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
import json
import httpx
_LOCK = threading.Lock()
_cached_offset: timedelta | None = None
_cached_at_utc: datetime | None = None
_cached_source: str | None = None
_DEFAULT_URLS = [
# Prefer HTTP to avoid TLS issues when local clock is skewed
'http://www.baidu.com',
'http://www.qq.com',
'http://www.aliyun.com',
# China-friendly time APIs
'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp',
'http://quan.suning.com/getSysTime.do',
# Time API fallback
'http://worldtimeapi.org/api/timezone/Asia/Shanghai',
]
def get_time_sync_status() -> dict:
local_utc = datetime.now(timezone.utc)
with _LOCK:
enabled = str(os.environ.get('WGJY_DISABLE_TIME_SYNC', '')).strip() != '1'
offset = _cached_offset
last_refresh = _cached_at_utc
source = _cached_source
synced_utc = local_utc if (not enabled or offset is None) else (local_utc + offset)
return {
'enabled': enabled,
'local_utc': local_utc.isoformat(),
'synced_utc': synced_utc.isoformat(),
'offset_seconds': (synced_utc - local_utc).total_seconds(),
'last_refresh_utc': last_refresh.isoformat() if last_refresh else None,
'source': source,
}
def _parse_worldtimeapi_utc(text: str) -> datetime | None:
try:
obj = json.loads(text)
dt_text = obj.get('utc_datetime') or obj.get('datetime')
if isinstance(dt_text, str) and dt_text:
dt = datetime.fromisoformat(dt_text.replace('Z', '+00:00'))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
unixtime = obj.get('unixtime')
if isinstance(unixtime, (int, float)):
return datetime.fromtimestamp(float(unixtime), tz=timezone.utc)
except Exception:
return None
def _parse_taobao_utc(text: str) -> datetime | None:
try:
obj = json.loads(text)
t = (obj.get('data') or {}).get('t')
if isinstance(t, str) and t.isdigit():
ms = int(t)
return datetime.fromtimestamp(ms / 1000.0, tz=timezone.utc)
if isinstance(t, (int, float)):
return datetime.fromtimestamp(float(t) / 1000.0, tz=timezone.utc)
except Exception:
return None
return None
def _parse_suning_utc(text: str) -> datetime | None:
try:
obj = json.loads(text)
# example: {"sysTime2":"2026-01-23 12:34:56"}
s = obj.get('sysTime2') or obj.get('sysTime1')
if isinstance(s, str) and s:
bj_tz = timezone(timedelta(hours=8))
dt = datetime.strptime(s.strip(), '%Y-%m-%d %H:%M:%S').replace(tzinfo=bj_tz)
return dt.astimezone(timezone.utc)
except Exception:
return None
return None
def _try_fetch_utc_from_url(url: str) -> datetime | None:
try:
with httpx.Client(timeout=2.0, follow_redirects=True) as client:
use_get = any(k in url for k in ('worldtimeapi.org', 'api.m.taobao.com', 'suning.com'))
if use_get:
r = client.get(url)
else:
try:
r = client.head(url)
except Exception:
r = client.get(url)
try:
ct = (r.headers.get('content-type') or '').lower()
if 'application/json' in ct or r.text.strip().startswith('{'):
if 'worldtimeapi.org' in url:
dt = _parse_worldtimeapi_utc(r.text)
if dt is not None:
return dt
if 'api.m.taobao.com' in url:
dt = _parse_taobao_utc(r.text)
if dt is not None:
return dt
if 'suning.com' in url:
dt = _parse_suning_utc(r.text)
if dt is not None:
return dt
except Exception:
pass
date_str = r.headers.get('date')
if not date_str:
return None
dt = parsedate_to_datetime(date_str)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
except Exception:
return None
def _refresh_offset_if_needed() -> None:
global _cached_offset, _cached_at_utc, _cached_source
now = datetime.now(timezone.utc)
if _cached_offset is not None and _cached_at_utc is not None:
if (now - _cached_at_utc).total_seconds() < 300:
return
urls = _DEFAULT_URLS
try:
env_urls = str(os.environ.get('WGJY_TIME_SYNC_URLS', '')).strip()
if env_urls:
urls = [u.strip() for u in env_urls.split(',') if u.strip()]
except Exception:
pass
for url in urls:
net_utc = _try_fetch_utc_from_url(url)
if net_utc is None:
continue
local_utc = datetime.now(timezone.utc)
_cached_offset = net_utc - local_utc
_cached_at_utc = now
_cached_source = url
return
_cached_at_utc = now
def now_utc() -> datetime:
if str(os.environ.get('WGJY_DISABLE_TIME_SYNC', '')).strip() == '1':
return datetime.now(timezone.utc)
with _LOCK:
_refresh_offset_if_needed()
if _cached_offset is None:
return datetime.now(timezone.utc)
return datetime.now(timezone.utc) + _cached_offset