82 lines
2.9 KiB
Python
82 lines
2.9 KiB
Python
"""星盘最小实现:由「出生日期 + 出生时间 + 时区」算太阳/月亮所在星座。
|
||
|
||
算法用瑞士星历(Swiss Ephemeris)的 Moshier 解析式,不依赖星历数据文件:
|
||
太阳黄经误差 < 1″,月亮 < 0.1″,比「按日期查表」的近似算法稳得多,
|
||
临近星座交界(比如 3 月 21 日 0 点)也不会判错。
|
||
|
||
要点:
|
||
* 出生时间按出生地时区解释成 UTC —— 1986~1991 年内地实行过夏令时,
|
||
``zoneinfo`` 带历史规则,能自动扣掉那一小时;
|
||
* 黄经 0° = 白羊座 0°,每 30° 一个星座,序号与 ``zodiac_signs.sort_order`` 一致。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from datetime import date, datetime, time, timezone
|
||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||
|
||
import swisseph as swe
|
||
|
||
# 黄经顺序,作为码表缺行时的兜底
|
||
ZODIAC_ORDER: tuple[str, ...] = (
|
||
"aries", "taurus", "gemini", "cancer", "leo", "virgo",
|
||
"libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces",
|
||
)
|
||
|
||
DEFAULT_TZ = "Asia/Shanghai"
|
||
|
||
# 不传出生时间时按中午 12 点算:此时太阳/月亮都在当日中间位置,
|
||
# 交界日也不会因为「差几小时」翻到相邻星座
|
||
DEFAULT_TIME = time(12, 0)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class AstroResult:
|
||
sun_sign: str
|
||
moon_sign: str
|
||
sun_degree: float # 星座内度数 0~30
|
||
moon_degree: float
|
||
sun_lon: float # 绝对黄经 0~360
|
||
moon_lon: float
|
||
tz: str
|
||
utc_time: str
|
||
|
||
|
||
def _jd_ut(dt_local: datetime, tz_name: str) -> tuple[float, datetime]:
|
||
try:
|
||
tz = ZoneInfo(tz_name)
|
||
except (ZoneInfoNotFoundError, ValueError):
|
||
tz, tz_name = ZoneInfo(DEFAULT_TZ), DEFAULT_TZ
|
||
local = dt_local if dt_local.tzinfo else dt_local.replace(tzinfo=tz)
|
||
utc = local.astimezone(timezone.utc)
|
||
hours = utc.hour + utc.minute / 60 + utc.second / 3600 + utc.microsecond / 3.6e9
|
||
return swe.julday(utc.year, utc.month, utc.day, hours), utc
|
||
|
||
|
||
def _sign(lon: float) -> tuple[str, float]:
|
||
lon %= 360.0
|
||
return ZODIAC_ORDER[int(lon // 30.0) % 12], round(lon % 30.0, 2)
|
||
|
||
|
||
def compute(birthday: date, birth_time: time | None = None, tz: str = DEFAULT_TZ) -> AstroResult:
|
||
jd, utc = _jd_ut(datetime.combine(birthday, birth_time or DEFAULT_TIME), tz)
|
||
|
||
# FLG_MOSEPH:强制内置解析式,不需要 sepl_*.se1,部署零外部文件
|
||
flags = swe.FLG_MOSEPH | swe.FLG_SPEED
|
||
sun_lon = swe.calc_ut(jd, swe.SUN, flags)[0][0] % 360.0
|
||
moon_lon = swe.calc_ut(jd, swe.MOON, flags)[0][0] % 360.0
|
||
|
||
sun_sign, sun_deg = _sign(sun_lon)
|
||
moon_sign, moon_deg = _sign(moon_lon)
|
||
return AstroResult(
|
||
sun_sign=sun_sign,
|
||
moon_sign=moon_sign,
|
||
sun_degree=sun_deg,
|
||
moon_degree=moon_deg,
|
||
sun_lon=round(sun_lon, 4),
|
||
moon_lon=round(moon_lon, 4),
|
||
tz=tz,
|
||
utc_time=utc.isoformat(timespec="minutes"),
|
||
)
|