Files

72 lines
3.0 KiB
Python
Executable File

#!/usr/bin/env python3
# moonphase - moon phase calculator from the date (algorithmic, no network)
# Usage: moonphase [--date YYYY-MM-DD] [--json]
import argparse, datetime, json, math, sys
# Synodic month and a known new moon: 2000-01-06 18:14 UTC (JD 2451550.26)
SYNODIC = 29.530588853
NEW_MOON_JD = 2451550.26
NAMES = [
(0.0, 1.0, "New Moon"), (1.0, 6.38, "Waxing Crescent"), (6.38, 8.38, "First Quarter"),
(8.38, 13.77, "Waxing Gibbous"), (13.77, 15.77, "Full Moon"), (15.77, 21.14, "Waning Gibbous"),
(21.14, 23.14, "Last Quarter"), (23.14, 28.53, "Waning Crescent"), (28.53, 29.54, "New Moon"),
]
EMOJI = {"New Moon": "🌑", "Waxing Crescent": "🌒", "First Quarter": "🌓",
"Waxing Gibbous": "🌔", "Full Moon": "🌕", "Waning Gibbous": "🌖",
"Last Quarter": "🌗", "Waning Crescent": "🌘"}
def julian_day(d):
# d: datetime (UTC, naive treated as UTC)
return d.toordinal() + 1721425 - 0.5 + (d.hour * 3600 + d.minute * 60 + d.second) / 86400.0
def phase(dt):
jd = julian_day(dt)
age = (jd - NEW_MOON_JD) % SYNODIC
illum = (1 - math.cos(2 * math.pi * age / SYNODIC)) / 2 * 100
name = "New Moon"
for lo, hi, n in NAMES:
if lo <= age < hi:
name = n; break
return {"date": dt.date().isoformat(), "age_days": round(age, 2),
"illumination_pct": round(illum, 1), "phase": name,
"emoji": EMOJI[name], "fraction": round(age / SYNODIC, 3)}
def selftest():
# Known anchors: 2000-01-06 was a new moon; 2000-01-21 was (near) full.
p1 = phase(datetime.datetime(2000, 1, 6, 18, 14))
# Anchor is a rounded JD, so age may sit just either side of 0 / 29.53
assert p1["phase"] == "New Moon" and (p1["age_days"] < 1.0 or p1["age_days"] > 28.5), p1
p2 = phase(datetime.datetime(2000, 1, 21, 12, 0))
assert p2["phase"] == "Full Moon", p2
assert p2["illumination_pct"] > 90, p2
p3 = phase(datetime.datetime(2026, 12, 3))
assert 0 <= p3["illumination_pct"] <= 100 and p3["phase"] in EMOJI
print(p1); print(p2); print(p3)
print("moonphase selftest OK")
def main():
p = argparse.ArgumentParser(description="Moon phase calculator from the date (algorithmic, no network).")
p.add_argument("--date", default=None, help="date YYYY-MM-DD (default: today)")
p.add_argument("--json", action="store_true", help="output JSON")
p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
a = p.parse_args()
if a.selftest:
selftest(); return 0
if a.date:
try:
dt = datetime.datetime.fromisoformat(a.date)
except ValueError:
p.error("date must be YYYY-MM-DD")
else:
dt = datetime.datetime.now()
r = phase(dt)
if a.json:
print(json.dumps(r))
else:
print(f"{r['emoji']} {r['phase']} — {r['date']}")
print(f"Age: {r['age_days']} days Illumination: {r['illumination_pct']}% Cycle: {r['fraction']*100:.1f}%")
return 0
if __name__ == "__main__":
sys.exit(main())