Spaces:
Sleeping
Sleeping
File size: 5,259 Bytes
5bde3f1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | """
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}")
|