Resonance-Calc / core /time_manager.py
SergeyO7's picture
Upload 25 files
790625d verified
from timezonefinder import TimezoneFinder
import pytz
from datetime import datetime, timedelta
from typing import Optional # ADD THIS IMPORT
class TimeManager:
def __init__(self):
self.tf = TimezoneFinder()
self._timezone_cache = {}
def get_precise_timezone(self, lat: float, lon: float) -> str:
"""Точное определение временной зоны по координатам с кэшированием"""
cache_key = f"{lat:.4f},{lon:.4f}"
if cache_key not in self._timezone_cache:
self._timezone_cache[cache_key] = self.tf.timezone_at(lng=lon, lat=lat) or "UTC"
return self._timezone_cache[cache_key]
def localize_datetime(self, dt: datetime, tz_str: str) -> datetime:
"""Создание локализованного datetime"""
tz = pytz.timezone(tz_str)
if dt.tzinfo is None:
return tz.localize(dt)
return dt.astimezone(tz)
def convert_utc_to_local(self, utc_dt: datetime, tz_str: str) -> datetime:
"""Конвертация UTC в локальное время"""
tz = pytz.timezone(tz_str)
return utc_dt.astimezone(tz)
def get_timezone_info(self, tz_str: str, target_date: Optional[datetime] = None) -> dict: # FIXED: Optional[datetime]
"""Полная информация о временной зоне (с учетом DST)"""
tz = pytz.timezone(tz_str)
if target_date is None: # FIXED: Explicit None check
target_date = datetime.now()
localized = tz.localize(target_date)
return {
'name': tz_str,
'utc_offset': localized.utcoffset(),
'dst_offset': localized.dst(),
'is_dst': localized.dst() != timedelta(0),
'tz_name': localized.tzname()
}
# Глобальный экземпляр для использования во всех модулях
time_manager = TimeManager()