import math from dataclasses import dataclass from datetime import date, datetime, timedelta, timezone _SUN_ALTITUDE = -0.833 _CIVIL_ALTITUDE = -6.0 _GOLDEN_ALTITUDE = 6.0 @dataclass(frozen=True) class SunTimes: sunrise_at: datetime sunset_at: datetime dusk_end_at: datetime sunset_azimuth: int dawn_start_at: datetime sunrise_azimuth: int golden_start_at: datetime golden_end_at: datetime # 아침에 해 고도가 골든아워 높이까지 올라오는 때 def _solar(d: date, lon: float) -> tuple[float, float]: """NOAA 근사식. (태양 적위 도, 남중 시각 UTC 분).""" g = 2 * math.pi / 365 * (d.timetuple().tm_yday - 1) eqtime = 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) ) return math.degrees(decl), 720 - 4 * lon - eqtime def _hour_angle(lat: float, decl: float, altitude: float) -> float: phi, dl = math.radians(lat), math.radians(decl) cos_h = (math.sin(math.radians(altitude)) - math.sin(phi) * math.sin(dl)) / (math.cos(phi) * math.cos(dl)) return math.degrees(math.acos(max(-1.0, min(1.0, cos_h)))) def sun_times(d: date, lat: float, lon: float) -> SunTimes: decl, noon_min = _solar(d, lon) base = datetime(d.year, d.month, d.day, tzinfo=timezone.utc) at = lambda minutes: base + timedelta(minutes=minutes) # noqa: E731 h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4 h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4 h_golden = _hour_angle(lat, decl, _GOLDEN_ALTITUDE) * 4 phi, dl = math.radians(lat), math.radians(decl) azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi))))) return SunTimes( sunrise_at=at(noon_min - h_sun), sunset_at=at(noon_min + h_sun), dusk_end_at=at(noon_min + h_civil), sunset_azimuth=round(360 - azimuth), dawn_start_at=at(noon_min - h_civil), sunrise_azimuth=round(azimuth), golden_start_at=at(noon_min + h_golden), golden_end_at=at(noon_min - h_golden), )