polycorr-backend / time_utils.py
dhruv575
Initial build
5bde3f1
"""
Time Conversion Utilities
Handles conversion between Unix timestamps and EST datetime
"""
from datetime import datetime, timezone
import pytz
class TimeConverter:
"""Class to handle time conversions between Unix timestamps and EST"""
# Eastern Time Zone (handles both EST and EDT automatically)
EST = pytz.timezone('US/Eastern')
def __init__(self):
pass
def est_to_unix(self, est_datetime_str: str) -> int:
"""
Convert EST datetime string to Unix timestamp
Args:
est_datetime_str: DateTime string in EST timezone
Supported formats:
- "YYYY-MM-DD HH:MM:SS"
- "YYYY-MM-DD HH:MM"
- "MM/DD/YYYY HH:MM:SS"
- "MM/DD/YYYY HH:MM"
Returns:
Unix timestamp (seconds since epoch)
Example:
>>> converter = TimeConverter()
>>> converter.est_to_unix("2025-01-15 10:30:00")
1736954400
"""
# Try different datetime formats
formats = [
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%m/%d/%Y %H:%M:%S",
"%m/%d/%Y %H:%M",
"%Y-%m-%d",
]
dt = None
for fmt in formats:
try:
dt = datetime.strptime(est_datetime_str, fmt)
break
except ValueError:
continue
if dt is None:
raise ValueError(
f"Could not parse datetime string: {est_datetime_str}. "
f"Supported formats: YYYY-MM-DD HH:MM:SS, MM/DD/YYYY HH:MM:SS, etc."
)
# Localize to EST timezone
est_dt = self.EST.localize(dt)
# Convert to Unix timestamp
unix_timestamp = int(est_dt.timestamp())
return unix_timestamp
def unix_to_est(self, unix_timestamp: int) -> str:
"""
Convert Unix timestamp to EST datetime string
Args:
unix_timestamp: Unix timestamp (seconds since epoch)
Returns:
Datetime string in EST timezone (format: "YYYY-MM-DD HH:MM:SS EST")
Example:
>>> converter = TimeConverter()
>>> converter.unix_to_est(1736954400)
"2025-01-15 10:30:00 EST"
"""
# Create UTC datetime from timestamp
utc_dt = datetime.fromtimestamp(unix_timestamp, tz=timezone.utc)
# Convert to EST
est_dt = utc_dt.astimezone(self.EST)
# Format as string
return est_dt.strftime("%Y-%m-%d %H:%M:%S %Z")
def unix_to_est_datetime(self, unix_timestamp: int) -> datetime:
"""
Convert Unix timestamp to EST datetime object
Args:
unix_timestamp: Unix timestamp (seconds since epoch)
Returns:
Datetime object in EST timezone
"""
# Create UTC datetime from timestamp
utc_dt = datetime.fromtimestamp(unix_timestamp, tz=timezone.utc)
# Convert to EST
est_dt = utc_dt.astimezone(self.EST)
return est_dt
def validate_time_range(self, start_unix: int, end_unix: int) -> bool:
"""
Validate that start time is before end time
Args:
start_unix: Start time Unix timestamp
end_unix: End time Unix timestamp
Returns:
True if valid, raises ValueError if invalid
"""
if start_unix >= end_unix:
raise ValueError(
f"Start time ({self.unix_to_est(start_unix)}) must be before "
f"end time ({self.unix_to_est(end_unix)})"
)
return True
# Example usage and tests
if __name__ == "__main__":
converter = TimeConverter()
print("=== Time Conversion Examples ===\n")
# Test EST to Unix
test_datetime = "2025-11-15 14:30:00"
print(f"EST to Unix:")
print(f" Input: {test_datetime}")
unix_ts = converter.est_to_unix(test_datetime)
print(f" Output: {unix_ts}\n")
# Test Unix to EST
print(f"Unix to EST:")
print(f" Input: {unix_ts}")
est_str = converter.unix_to_est(unix_ts)
print(f" Output: {est_str}\n")
# Test different date formats
print("Testing different input formats:")
test_formats = [
"2025-11-15 14:30:00",
"2025-11-15 14:30",
"11/15/2025 14:30:00",
"11/15/2025 14:30",
"2025-11-15"
]
for fmt in test_formats:
try:
unix = converter.est_to_unix(fmt)
est = converter.unix_to_est(unix)
print(f" {fmt:<25} -> {unix} -> {est}")
except Exception as e:
print(f" {fmt:<25} -> Error: {e}")
print("\nValidation test:")
try:
start = converter.est_to_unix("2025-11-15 10:00:00")
end = converter.est_to_unix("2025-11-15 18:00:00")
converter.validate_time_range(start, end)
print(f" ✓ Valid time range")
except ValueError as e:
print(f" ✗ {e}")