Files
o2o-weather/backend/services/calc/day_slot.py
T

35 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from datetime import date, datetime, time, timedelta
from common.utils.kma_time import KST
SLOTS = ("morning", "day", "evening", "night")
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
NIGHT_END_HOUR = 5
EVENING_EARLIEST_HOUR = 17 # 겨울엔 일몰 2시간 전이 15시대라, 사람들이 아직 낮으로 느끼는 오후 3시가 저녁이 되지 않게
def evening_start(sunset_at: datetime) -> datetime:
"""저녁이 시작하는 시각: 일몰 2시간 전, 단 17시보다 이르지 않게."""
sunset = sunset_at.astimezone(KST)
return max(sunset - timedelta(hours=2), sunset.replace(hour=EVENING_EARLIEST_HOUR, minute=0, second=0, microsecond=0))
def slot_of(now: datetime, sunset_at: datetime) -> str:
"""아침 05–11 · 낮 11–저녁 시작 · 저녁 일몰 2시간 전(17시보다 이르지 않게)–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
h = now.hour
if NIGHT_END_HOUR <= h < 11:
return "morning"
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
return "day" if now < evening_start(sunset_at) else "evening"
return "night"
def slot_hours(day: date, sunset_at: datetime) -> dict[str, set[int]]:
"""그날 5시~다음 날 5시를 구간별 시각으로 나눈다. 24 이상은 다음 날 시각. 한 시간은 그 30분 시점의 구간에 넣는다."""
out: dict[str, set[int]] = {s: set() for s in SLOTS}
start = datetime.combine(day, time(0), tzinfo=KST)
for h in range(NIGHT_END_HOUR, 24 + NIGHT_END_HOUR):
out[slot_of(start + timedelta(hours=h, minutes=30), sunset_at)].add(h)
return out