From 73a847f28849a181a52353a0eb7346787370af8b Mon Sep 17 00:00:00 2001 From: Houkime <> Date: Fri, 10 Nov 2023 12:19:32 +0000 Subject: [PATCH] feature(time): timestamp parsers --- selfprivacy_api/utils/time.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 selfprivacy_api/utils/time.py diff --git a/selfprivacy_api/utils/time.py b/selfprivacy_api/utils/time.py new file mode 100644 index 0000000..5eb7e04 --- /dev/null +++ b/selfprivacy_api/utils/time.py @@ -0,0 +1,30 @@ +from datetime import datetime, timezone + + +def tzaware_parse_time(iso_timestamp: str) -> datetime: + """ + parse an iso8601 timestamp into timezone-aware datetime + assume utc if no timezone in stamp + example of timestamp: + 2023-11-10T12:07:47.868788+00:00 + + """ + dt = datetime.fromisoformat(iso_timestamp) + if dt.tzinfo is None: + dt = dt.astimezone(timezone.utc) + return dt + + +def tzaware_parse_time_strict(iso_timestamp: str) -> datetime: + """ + parse an iso8601 timestamp into timezone-aware datetime + raise an error if no timezone in stamp + example of timestamp: + 2023-11-10T12:07:47.868788+00:00 + + """ + dt = datetime.fromisoformat(iso_timestamp) + if dt.tzinfo is None: + raise ValueError("no timezone in timestamp", iso_timestamp) + dt = dt.astimezone(timezone.utc) + return dt