"""Sun elevation from date/time and position (NOAA approximation, ±0.5°).""" import math from datetime import datetime, timezone def elevation(when: datetime, lat: float, lon: float) -> float: when = when.astimezone(timezone.utc) day_of_year = when.timetuple().tm_yday hours = when.hour + when.minute / 60 + when.second / 3600 g = 2 * math.pi / 365 * (day_of_year - 1 + (hours - 12) / 24) eq_time = 229.18 * ( 0.000075 + 0.001868 * math.cos(g) - 0.032077 * math.sin(g) - 0.014615 * math.cos(2 * g) - 0.040849 * math.sin(2 * g) ) decl = ( 0.006918 - 0.399912 * math.cos(g) + 0.070257 * math.sin(g) - 0.006758 * math.cos(2 * g) + 0.000907 * math.sin(2 * g) - 0.002697 * math.cos(3 * g) + 0.00148 * math.sin(3 * g) ) true_solar_minutes = hours * 60 + eq_time + 4 * lon hour_angle = math.radians(true_solar_minutes / 4 - 180) lat_r = math.radians(lat) cos_zenith = math.sin(lat_r) * math.sin(decl) + math.cos(lat_r) * math.cos(decl) * math.cos( hour_angle ) return 90 - math.degrees(math.acos(max(-1.0, min(1.0, cos_zenith))))