#!/usr/bin/env python3 """Часовой пояс, смещение UTC и переходы на летнее время.""" from __future__ import annotations import argparse import json import os import platform import subprocess import sys import time from datetime import datetime, timezone from pathlib import Path from zoneinfo import ZoneInfo def zone_name() -> str: system = platform.system() if system == "Linux": path = Path("/etc/timezone") if path.is_file(): text = path.read_text(encoding="utf-8", errors="replace").strip() if text: return text link = Path("/etc/localtime") if link.is_symlink(): target = os.readlink(link) if "zoneinfo/" in target: return target.split("zoneinfo/", 1)[1] elif system == "Darwin": link = Path("/etc/localtime") if link.is_symlink(): target = os.readlink(link) if "zoneinfo/" in target: return target.split("zoneinfo/", 1)[1] elif system == "Windows": result = subprocess.run( ["tzutil", "/g"], capture_output=True, text=True, check=False, ) if result.returncode == 0: return result.stdout.strip() return "" def dst_months(zone: str) -> list[str]: months = [] now = datetime.now() if zone and platform.system() != "Windows": try: info = ZoneInfo(zone) except Exception: info = None if info is not None: for month in range(1, 13): moment = datetime(now.year, month, 15, 12, 0, tzinfo=info) if moment.dst() and moment.dst().total_seconds() != 0: months.append(moment.strftime("%B")) return months for month in range(1, 13): stamp = time.mktime((now.year, month, 15, 12, 0, 0, 0, 0, -1)) if time.localtime(stamp).tm_isdst > 0: months.append(time.strftime("%B", time.localtime(stamp))) return months def main() -> int: parser = argparse.ArgumentParser(description="Часовой пояс и смещение UTC") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() local = datetime.now().astimezone() utc = datetime.now(timezone.utc) offset = local.utcoffset() offset_hours = offset.total_seconds() / 3600 if offset else 0.0 name = zone_name() months = dst_months(name) print(f"Часовой пояс: {name or 'не определён'}") print(f"Местное время: {local.strftime('%Y-%m-%d %H:%M:%S %Z')}") print(f"UTC: {utc.strftime('%Y-%m-%d %H:%M:%S')}") print(f"Смещение UTC: {offset_hours:+.1f} ч") print(f"Летнее время сейчас: {'да' if local.dst() else 'нет'}") print(f"Месяцы летнего времени: {', '.join(months) if months else 'нет'}") if args.json: args.json.parent.mkdir(parents=True, exist_ok=True) payload = { "zone": name, "local": local.isoformat(), "utc": utc.isoformat(), "offset_hours": offset_hours, "dst_now": bool(local.dst()), "dst_months": months, } args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"JSON сохранён: {args.json}") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except KeyboardInterrupt: print("Прервано пользователем", file=sys.stderr) raise SystemExit(130)