76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
"""列表/导出用 UTC 时间窗(Gate / Binance 主站共用)。"""
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
PRESET_UTC_TODAY = "utc_today"
|
|
PRESET_UTC_LAST24H = "utc_last24h"
|
|
PRESET_UTC_LAST7D = "utc_last7d"
|
|
PRESET_CUSTOM = "custom"
|
|
|
|
|
|
def utc_now():
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def utc_today_bounds(now=None):
|
|
now = now or utc_now()
|
|
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
return start, now
|
|
|
|
|
|
def resolve_window(query_mapping, default_preset=PRESET_UTC_TODAY):
|
|
"""
|
|
从 ?win_preset= & from_utc= & to_utc= 解析窗口。
|
|
返回 dict: preset, start_utc, end_utc, label, start_ms, end_ms
|
|
"""
|
|
preset = (query_mapping.get("win_preset") or default_preset or PRESET_UTC_TODAY).strip().lower()
|
|
now = utc_now()
|
|
|
|
if preset == PRESET_UTC_LAST24H:
|
|
start = now - timedelta(hours=24)
|
|
end = now
|
|
label = "近24小时(UTC)"
|
|
elif preset == PRESET_UTC_LAST7D:
|
|
start = now - timedelta(days=7)
|
|
end = now
|
|
label = "近7天(UTC)"
|
|
elif preset == PRESET_CUSTOM:
|
|
start = _parse_utc_input(query_mapping.get("from_utc")) or utc_today_bounds(now)[0]
|
|
end = _parse_utc_input(query_mapping.get("to_utc")) or now
|
|
if end < start:
|
|
start, end = end, start
|
|
label = f"{start.strftime('%Y-%m-%d %H:%M')} ~ {end.strftime('%Y-%m-%d %H:%M')} UTC"
|
|
else:
|
|
start, end = utc_today_bounds(now)
|
|
preset = PRESET_UTC_TODAY
|
|
label = f"UTC当日 {start.strftime('%Y-%m-%d')}"
|
|
|
|
return {
|
|
"preset": preset,
|
|
"start_utc": start,
|
|
"end_utc": end,
|
|
"label": label,
|
|
"start_ms": int(start.timestamp() * 1000),
|
|
"end_ms": int(end.timestamp() * 1000),
|
|
}
|
|
|
|
|
|
def _parse_utc_input(raw):
|
|
s = (raw or "").strip().replace("T", " ").replace("Z", "").strip()
|
|
if not s:
|
|
return None
|
|
for fmt, n in (("%Y-%m-%d %H:%M:%S", 19), ("%Y-%m-%d %H:%M", 16), ("%Y-%m-%d", 10)):
|
|
try:
|
|
dt = datetime.strptime(s[:n], fmt)
|
|
return dt.replace(tzinfo=timezone.utc)
|
|
except Exception:
|
|
continue
|
|
return None
|
|
|
|
|
|
def utc_window_to_bj_sql_strings(start_utc, end_utc, app_tz):
|
|
"""DB 存北京时间字符串时,用于 SQLite 字符串范围比较。"""
|
|
start_bj = start_utc.astimezone(app_tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
end_bj = end_utc.astimezone(app_tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
return start_bj, end_bj
|