103 lines
4.3 KiB
Python
Executable File
103 lines
4.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# sunrise - sunrise/sunset calculator for a given latitude/longitude (algorithmic)
|
|
# Usage: sunrise --lat LAT --lon LON [--date YYYY-MM-DD] [--tz OFFSET]
|
|
# NOAA solar calculation; no network needed.
|
|
import argparse, datetime, math, sys
|
|
|
|
def _sun_time(lat, lon, date, tz_hours, rising):
|
|
# NOAA algorithm; returns local time as datetime or None (polar day/night)
|
|
lat_r = math.radians(lat)
|
|
n = date.timetuple().tm_yday
|
|
lng_hour = lon / 15.0
|
|
t = n + ((6 if rising else 18) - lng_hour) / 24.0
|
|
m = (0.9856 * t) - 3.289
|
|
l = m + 1.916 * math.sin(math.radians(m)) + 0.020 * math.sin(math.radians(2 * m)) + 282.634
|
|
l %= 360
|
|
ra = math.degrees(math.atan(0.91764 * math.tan(math.radians(l)))) % 360
|
|
l_quad = (math.floor(l / 90) * 90)
|
|
ra_quad = (math.floor(ra / 90) * 90)
|
|
ra += l_quad - ra_quad
|
|
ra /= 15.0
|
|
sin_dec = 0.39782 * math.sin(math.radians(l))
|
|
cos_dec = math.cos(math.asin(sin_dec))
|
|
cos_h = (math.cos(math.radians(90.833)) - sin_dec * math.sin(lat_r)) / (cos_dec * math.cos(lat_r))
|
|
if cos_h > 1:
|
|
return None # sun never rises
|
|
if cos_h < -1:
|
|
return None # sun never sets
|
|
h = math.degrees(math.acos(cos_h))
|
|
if rising:
|
|
h = 360 - h
|
|
h /= 15.0
|
|
t_local = h + ra - (0.06571 * t) - 6.622
|
|
ut = (t_local - lng_hour) % 24
|
|
local = (ut + tz_hours) % 24
|
|
hour = int(local)
|
|
minute = int(round((local - hour) * 60))
|
|
if minute == 60:
|
|
hour, minute = (hour + 1) % 24, 0
|
|
return datetime.datetime(date.year, date.month, date.day, hour, minute)
|
|
|
|
def calc(lat, lon, date, tz_hours):
|
|
rise = _sun_time(lat, lon, date, tz_hours, True)
|
|
set_ = _sun_time(lat, lon, date, tz_hours, False)
|
|
day_len = None
|
|
if rise and set_:
|
|
day_len = set_ - rise
|
|
if day_len.total_seconds() < 0:
|
|
day_len += datetime.timedelta(days=1)
|
|
return rise, set_, day_len
|
|
|
|
def fmt(dt):
|
|
return dt.strftime("%H:%M") if dt else "—"
|
|
|
|
def selftest():
|
|
# New York City, summer solstice 2026 (EDT, UTC-4): sunrise ~05:24, sunset ~20:30
|
|
d = datetime.date(2026, 6, 21)
|
|
rise, set_, length = calc(40.7128, -74.0060, d, -4)
|
|
assert rise and set_, (rise, set_)
|
|
assert rise.hour == 5 and 15 <= rise.minute <= 35, rise
|
|
assert set_.hour == 20 and 20 <= set_.minute <= 40, set_
|
|
assert length and 14 * 3600 < length.total_seconds() < 16 * 3600, length
|
|
# Equator on equinox: ~12h day
|
|
r2, s2, l2 = calc(0.0, 0.0, datetime.date(2026, 3, 20), 0)
|
|
assert l2 and abs(l2.total_seconds() - 12 * 3600) < 1800, l2
|
|
print(f"NYC 2026-06-21: sunrise {fmt(rise)} sunset {fmt(set_)} day {length}")
|
|
print("sunrise selftest OK")
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description="Sunrise/sunset calculator for a given latitude/longitude (algorithmic).")
|
|
p.add_argument("--lat", type=float, required=False, default=None, help="latitude in degrees (-90..90)")
|
|
p.add_argument("--lon", type=float, required=False, default=None, help="longitude in degrees (-180..180)")
|
|
p.add_argument("--date", default=None, help="date YYYY-MM-DD (default: today)")
|
|
p.add_argument("--tz", type=float, default=0.0, help="timezone offset from UTC in hours (default 0)")
|
|
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.lat is None or a.lon is None:
|
|
p.error("--lat and --lon are required")
|
|
if not -90 <= a.lat <= 90 or not -180 <= a.lon <= 180:
|
|
p.error("latitude must be -90..90, longitude -180..180")
|
|
if a.date:
|
|
try:
|
|
date = datetime.date.fromisoformat(a.date)
|
|
except ValueError:
|
|
p.error("date must be YYYY-MM-DD")
|
|
else:
|
|
date = datetime.date.today()
|
|
rise, set_, length = calc(a.lat, a.lon, date, a.tz)
|
|
print(f"Sunrise/sunset for {a.lat}, {a.lon} on {date.isoformat()} (UTC{a.tz:+g})")
|
|
print(f" Sunrise: {fmt(rise)}")
|
|
print(f" Sunset: {fmt(set_)}")
|
|
if length:
|
|
h, rem = divmod(int(length.total_seconds()), 3600)
|
|
m, _ = divmod(rem, 60)
|
|
print(f" Day length: {h}h {m}m")
|
|
elif rise is None and set_ is None:
|
|
print(" Polar day or polar night — the sun does not rise/set this day.")
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|