[util] implement 'to_datetime()'

This commit is contained in:
Mike Fährmann
2025-05-28 20:10:18 +02:00
parent 129fc00962
commit 17b2910938
2 changed files with 80 additions and 0 deletions

View File

@@ -236,6 +236,34 @@ def to_string(value):
return str(value)
def to_datetime(value):
"""Convert 'value' to a datetime object"""
if not value:
return EPOCH
if isinstance(value, datetime.datetime):
return value
if isinstance(value, str):
try:
if value[-1] == "Z":
# compat for Python < 3.11
value = value[:-1]
dt = datetime.datetime.fromisoformat(value)
if dt.tzinfo is None:
if dt.microsecond:
dt = dt.replace(microsecond=0)
else:
# convert to naive UTC
dt = dt.astimezone(datetime.timezone.utc).replace(
microsecond=0, tzinfo=None)
return dt
except Exception:
pass
return text.parse_timestamp(value, EPOCH)
def datetime_to_timestamp(dt):
"""Convert naive UTC datetime to Unix timestamp"""
return (dt - EPOCH) / SECOND