2023-05-14 07:28:59 +00:00
|
|
|
from datetime import datetime, timezone
|
2023-05-14 08:45:07 +00:00
|
|
|
from typing import Optional
|
2023-05-14 07:28:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
def dt_now() -> datetime:
|
|
|
|
"""Return the current datetime in UTC."""
|
|
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
|
|
|
2023-05-14 08:45:07 +00:00
|
|
|
def dt_ts(dt: Optional[datetime] = None) -> int:
|
2023-05-14 08:43:06 +00:00
|
|
|
"""Return the current timestamp in ms as a timestamp in UTC."""
|
2023-05-14 08:45:07 +00:00
|
|
|
if dt:
|
|
|
|
return int(dt.timestamp() * 1000)
|
2023-05-14 08:43:06 +00:00
|
|
|
return int(dt_now().timestamp() * 1000)
|
|
|
|
|
|
|
|
|
2023-05-14 07:28:59 +00:00
|
|
|
def dt_from_ts(timestamp: float) -> datetime:
|
|
|
|
"""
|
|
|
|
Return a datetime from a timestamp.
|
|
|
|
:param timestamp: timestamp in seconds or milliseconds
|
|
|
|
"""
|
|
|
|
if timestamp > 1e10:
|
|
|
|
# Timezone in ms - convert to seconds
|
|
|
|
timestamp /= 1000
|
|
|
|
return datetime.fromtimestamp(timestamp, tz=timezone.utc)
|