timezone.py
1 """ 2 Timezone Utilities 3 4 Handles timezone conversion for dashboard display. 5 """ 6 7 from datetime import datetime 8 from zoneinfo import ZoneInfo 9 from dashboard import config 10 11 12 def to_local_time(utc_time_str, format="%Y-%m-%d %H:%M:%S"): 13 """ 14 Convert UTC timestamp string to local timezone. 15 16 Args: 17 utc_time_str: UTC timestamp string (e.g., "2026-02-10 00:04:13") 18 format: strftime format for output (default: "%Y-%m-%d %H:%M:%S") 19 20 Returns: 21 Formatted string in local timezone 22 """ 23 if not utc_time_str or utc_time_str == "Never": 24 return utc_time_str 25 26 try: 27 # Parse the UTC timestamp (SQLite returns UTC timestamps) 28 # Handle both with and without microseconds 29 utc_time = None 30 for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]: 31 try: 32 utc_time = datetime.strptime(utc_time_str, fmt) 33 break 34 except ValueError: 35 continue 36 37 if utc_time is None: 38 return utc_time_str # Return original if can't parse 39 40 # Add UTC timezone info 41 utc_time = utc_time.replace(tzinfo=ZoneInfo("UTC")) 42 43 # Convert to local timezone 44 local_time = utc_time.astimezone(ZoneInfo(config.TIMEZONE)) 45 46 # Format and return 47 return local_time.strftime(format) 48 49 except Exception as e: 50 # If conversion fails, return original 51 return utc_time_str 52 53 54 def to_local_datetime(utc_time_str): 55 """ 56 Convert UTC timestamp string to local timezone datetime object. 57 58 Args: 59 utc_time_str: UTC timestamp string 60 61 Returns: 62 datetime object in local timezone, or None if conversion fails 63 """ 64 if not utc_time_str or utc_time_str == "Never": 65 return None 66 67 try: 68 # Parse the UTC timestamp 69 utc_time = None 70 for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]: 71 try: 72 utc_time = datetime.strptime(utc_time_str, fmt) 73 break 74 except ValueError: 75 continue 76 77 if utc_time is None: 78 return None 79 80 # Add UTC timezone info and convert 81 utc_time = utc_time.replace(tzinfo=ZoneInfo("UTC")) 82 return utc_time.astimezone(ZoneInfo(config.TIMEZONE)) 83 84 except Exception: 85 return None