Form location line, chart page birth chips/出生时区 and transit caption, and the Chinese report's birth tables use one rule: +8 北京时间, +9 in a 1986-1991 summer 北京时间(夏令时), +6 at a Xinjiang place 新疆时间; elsewhere and English keep UTC. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
105 lines
4.0 KiB
Python
105 lines
4.0 KiB
Python
"""BUG-2405: the report's birth line says 「北京时间」 for a mainland China birth.
|
||
|
||
Mirrors ``frontend/src/lib/birth-clock-label.ts`` (``chinaBirthClockLabel``): +8 is 北京时间; +9 on a
|
||
date in China's 1986–1991 summer time is 北京时间(夏令时); +6 at a Xinjiang place (the 新疆时间
|
||
choice, BUG-2355) is 新疆时间. Anything else, a place outside mainland China, or the English edition
|
||
returns None and the caller keeps its UTC wording. The report packet carries no IANA id, so the zone is
|
||
looked up from the birth coordinates the same way ``/api/locations/timezone`` resolves it.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime
|
||
from functools import lru_cache
|
||
from typing import Any
|
||
from zoneinfo import ZoneInfo
|
||
|
||
CHINA_MAINLAND_ZONES = frozenset({
|
||
"Asia/Shanghai", "Asia/Urumqi", "Asia/Chongqing", "Asia/Chungking", "Asia/Harbin", "Asia/Kashgar", "PRC",
|
||
})
|
||
XINJIANG_ZONES = frozenset({"Asia/Urumqi", "Asia/Kashgar"})
|
||
|
||
_OFFSET = re.compile(r"(?:UTC|GMT)?\s*([+-]?)\s*(\d{1,2})(?::(\d{2})|(\.\d+))?")
|
||
|
||
|
||
def offset_hours(value: Any) -> float | None:
|
||
"""``8`` / ``8.0`` / ``"UTC+8.0"`` / ``"+08:00"`` → hours; anything else None."""
|
||
if isinstance(value, bool):
|
||
return None
|
||
if isinstance(value, (int, float)):
|
||
return float(value)
|
||
match = _OFFSET.fullmatch(str(value or "").strip().upper())
|
||
if not match:
|
||
return None
|
||
hours = int(match.group(2)) + (int(match.group(3)) / 60 if match.group(3) else float(match.group(4) or 0))
|
||
return -hours if match.group(1) == "-" else hours
|
||
|
||
|
||
@lru_cache(maxsize=1)
|
||
def _finder():
|
||
try:
|
||
from timezonefinder import TimezoneFinder
|
||
except ImportError: # pragma: no cover - dependency is in requirements.txt
|
||
return None
|
||
return TimezoneFinder()
|
||
|
||
|
||
@lru_cache(maxsize=256)
|
||
def _zone_at(lat: float, lon: float) -> str | None:
|
||
finder = _finder()
|
||
if finder is None or not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||
return None
|
||
try:
|
||
return finder.timezone_at(lng=lon, lat=lat)
|
||
except Exception: # pragma: no cover - defensive
|
||
return None
|
||
|
||
|
||
def _beijing_summer_time(birth_date: str) -> bool:
|
||
"""The birth year's Beijing offsets differ in January and July, and the date itself is on +9."""
|
||
match = re.match(r"(\d{4})-(\d{2})-(\d{2})", str(birth_date or ""))
|
||
if not match:
|
||
return False
|
||
zone = ZoneInfo("Asia/Shanghai")
|
||
year, month, day = (int(part) for part in match.groups())
|
||
january = datetime(year, 1, 15, 12, tzinfo=zone).utcoffset()
|
||
july = datetime(year, 7, 15, 12, tzinfo=zone).utcoffset()
|
||
if january == july:
|
||
return False
|
||
try:
|
||
on_day = datetime(year, month, day, 12, tzinfo=zone).utcoffset()
|
||
except ValueError:
|
||
return False
|
||
return on_day is not None and on_day.total_seconds() / 3600 > min(january, july).total_seconds() / 3600
|
||
|
||
|
||
def china_birth_clock_label(tz: Any, lat: Any, lon: Any, birth_date: Any = "", *, timezone_id: str | None = None) -> str | None:
|
||
"""「北京时间」「北京时间(夏令时)」「新疆时间」 for a mainland China birth, else None."""
|
||
hours = offset_hours(tz)
|
||
if hours is None:
|
||
return None
|
||
zone = timezone_id
|
||
if not zone:
|
||
try:
|
||
zone = _zone_at(round(float(lat), 4), round(float(lon), 4))
|
||
except (TypeError, ValueError):
|
||
return None
|
||
if zone not in CHINA_MAINLAND_ZONES:
|
||
return None
|
||
if hours == 8:
|
||
return "北京时间"
|
||
if hours == 9 and _beijing_summer_time(str(birth_date or "")):
|
||
return "北京时间(夏令时)"
|
||
if hours == 6 and zone in XINJIANG_ZONES:
|
||
return "新疆时间"
|
||
return None
|
||
|
||
|
||
def birth_offset_text(birth: dict, language: str, fallback: Any) -> Any:
|
||
"""The report's birth-line offset cell: the China clock name in the Chinese edition, else ``fallback``."""
|
||
if language == "en" or not isinstance(birth, dict):
|
||
return fallback
|
||
label = china_birth_clock_label(birth.get("tz"), birth.get("lat"), birth.get("lon"), birth.get("date"))
|
||
return label or fallback
|