Last active
July 26, 2025 05:51
-
-
Save gnowland/a2b43bcc9c369af33f9c995c258144ee to your computer and use it in GitHub Desktop.
Convert a timestamp to epoch timestamp int in milliseconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from dateutil import parser | |
def get_epoch(timestamp): | |
""" | |
Convert a timestamp to epoch timestamp int in milliseconds | |
Accepts timestamp in seconds or milliscons as a float OR an int, or a datetime-coercible string | |
Raises ValueError if the timestamp is not valid | |
""" | |
try: | |
# Attempt to convert to float; works for int, float, or floatable string. | |
timestamp_float = float(timestamp) | |
except (ValueError, TypeError) as e: | |
# if timestamp is not convertible to float and it's a string, try to coerce it to epoch time in milliseconds | |
if isinstance(timestamp, str): | |
try: | |
dt = parser.parse(timestamp) | |
print(f"datetime (parsed): {dt}") | |
epoch_sec = dt.timestamp() | |
# convert seconds to milliseconds | |
return int(epoch_sec * 1000) | |
except Exception as e: | |
raise ValueError(f"Dateutil parser could not parse '{timestamp}': {e}") | |
else: | |
raise ValueError(f"Timestamp '{timestamp}' is not convertible to float: {e}") | |
# timestamp is float-able, check if it's valid datetime | |
try: | |
# Validate timestamp is seconds | |
dt = datetime.fromtimestamp(timestamp_float) | |
print(f"datetime (seconds): {dt}") | |
# convert seconds to milliseconds | |
return int(timestamp_float * 1000) | |
# Note: datetime.fromtimestamp() raises OSError for out-of-range values on some systems. | |
except (TypeError, ValueError, OSError) as e: | |
# Validate timestamp is milliseconds | |
try: | |
dt = datetime.fromtimestamp(timestamp_float / 1000) | |
# timestamp is valid, already milliseconds | |
print(f"datetime (milliseconds): {dt}") | |
return int(timestamp_float) | |
# Note: datetime.fromtimestamp() raises OSError for out-of-range values on some systems. | |
except (TypeError, ValueError, OSError) as e: | |
raise ValueError(f"'{timestamp_float}' is not a valid timestamp: {e}") | |
# Various date-time string formats | |
date_strings = [ | |
"2025-05-30 08:48:56", | |
"1748594936000", | |
1748594936, | |
] | |
for date in date_strings: | |
try: | |
print(get_epoch(date)) | |
except ValueError as e: | |
print(f"Could not parse '{date}': {e}") | |
# All print: | |
# datetime (parsed): 2025-05-30 08:48:56 | |
# 1748594936000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment