aboutsummaryrefslogtreecommitdiffstats
path: root/hyprsunset_qt/sun.py
blob: bc611f95f1c9857587e5875892a40018dcf57223 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""Geolocation + sunrise/sunset lookup with a manual-refresh JSON cache."""

from __future__ import annotations

import json
from datetime import datetime, tzinfo
from pathlib import Path
from typing import Optional


def to_local_hm(iso_utc: str, tz: Optional[tzinfo] = None) -> str:
    """Convert an ISO-8601 UTC timestamp to local HH:MM."""
    dt = datetime.fromisoformat(iso_utc)
    local = dt.astimezone(tz)  # tz=None -> system local zone
    return local.strftime("%H:%M")


def read_cache(path: Path) -> Optional[dict]:
    path = Path(path)
    if not path.exists():
        return None
    try:
        return json.loads(path.read_text())
    except (json.JSONDecodeError, OSError):
        return None


def write_cache(payload: dict, path: Path) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2))