52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
|
|
"""
|
||
|
|
Time-related transformation utilities.
|
||
|
|
|
||
|
|
This module provides functions for handling timestamps and datetime conversions
|
||
|
|
in a consistent way across the application.
|
||
|
|
"""
|
||
|
|
|
||
|
|
from datetime import datetime, timezone
|
||
|
|
from typing import Any, Optional
|
||
|
|
from logging import Logger
|
||
|
|
|
||
|
|
|
||
|
|
def timestamp_to_datetime(
|
||
|
|
timestamp: Any,
|
||
|
|
is_milliseconds: bool = True,
|
||
|
|
logger: Optional[Logger] = None,
|
||
|
|
component_name: str = "time_utils"
|
||
|
|
) -> datetime:
|
||
|
|
"""
|
||
|
|
Convert various timestamp formats to timezone-aware datetime.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
timestamp: Timestamp in various formats
|
||
|
|
is_milliseconds: True if timestamp is in milliseconds
|
||
|
|
logger: Optional logger for error messages
|
||
|
|
component_name: Name for logging
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Timezone-aware datetime object
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
# Convert to int/float
|
||
|
|
if isinstance(timestamp, str):
|
||
|
|
timestamp_num = float(timestamp)
|
||
|
|
elif isinstance(timestamp, (int, float)):
|
||
|
|
timestamp_num = float(timestamp)
|
||
|
|
else:
|
||
|
|
raise ValueError(f"Invalid timestamp type: {type(timestamp)}")
|
||
|
|
|
||
|
|
# Convert to seconds if needed
|
||
|
|
if is_milliseconds:
|
||
|
|
timestamp_num = timestamp_num / 1000
|
||
|
|
|
||
|
|
# Create timezone-aware datetime
|
||
|
|
dt = datetime.fromtimestamp(timestamp_num, tz=timezone.utc)
|
||
|
|
return dt
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
if logger:
|
||
|
|
logger.error(f"{component_name}: Error converting timestamp {timestamp}: {e}")
|
||
|
|
# Return current time as fallback
|
||
|
|
return datetime.now(timezone.utc)
|