Skip to content

Instantly share code, notes, and snippets.

@Menziess
Created June 15, 2024 15:23
Show Gist options
  • Save Menziess/5ac48ee8e8972e3fc6dcbf7a7d98b998 to your computer and use it in GitHub Desktop.
Save Menziess/5ac48ee8e8972e3fc6dcbf7a7d98b998 to your computer and use it in GitHub Desktop.
from datetime import date
from datetime import datetime as dt
from typing import Union, cast
from dateutil.tz import tzlocal, tzutc
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
def int_to_timestamp(
value: int,
mode='MICROSECONDS',
format=DATETIME_FORMAT,
tz=tzutc(),
*,
as_datetime=False
) -> Union[str, dt, date]:
"""Convert integer milliseconds to datetime (string) (default UTC).
Raises KeyError if mode doesn't exist.
"""
denomenator = {
'DAYS': 1 / 86400,
'SECONDS': 1,
'MILLISECONDS': 1000,
'MICROSECONDS': 1000_000,
}[mode]
ts_value = dt.fromtimestamp(value / denomenator, tz=tz)
if not as_datetime:
return ts_value.strftime(format)
elif mode == 'DAYS':
return ts_value.date()
else:
return ts_value
def timestamp_to_int(
value: Union[str, dt, date],
mode='MICROSECONDS',
format=DATETIME_FORMAT,
tz=tzutc()
) -> int:
"""Convert datetime (string) to integer milliseconds (default UTC).
Raises KeyError if mode doesn't exist.
"""
if type(value) is date:
value = dt.combine(value, dt.min.time())
epoch = dt(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
ts = (
cast(dt, (
dt.strptime(value, format)
if isinstance(value, str)
else value
))
.astimezone(tzlocal())
.replace(tzinfo=tz)
)
diff = (ts - epoch).total_seconds()
res = {
'DAYS': diff / 86400,
'SECONDS': diff,
'MILLISECONDS': diff * 1000,
'MICROSECONDS': diff * 1000_000,
}[mode]
return int(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment