Skip to content

Commit 6c7ad0a

Browse files
authored
Convert timezone-aware datetimes automatically to UTC (#485)
1 parent 3a997d3 commit 6c7ad0a

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

mvt/common/utils.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,23 @@ def convert_chrometime_to_datetime(timestamp: int) -> datetime.datetime:
5353
def convert_datetime_to_iso(date_time: datetime.datetime) -> str:
5454
"""Converts datetime to ISO string.
5555
56-
:param datetime: datetime.
56+
:param datetime: datetime, naive or timezone aware
5757
:type datetime: datetime.datetime
5858
:returns: ISO datetime string in YYYY-mm-dd HH:MM:SS.ms format.
5959
:rtype: str
6060
6161
"""
6262
try:
63+
if date_time.tzinfo:
64+
# Timezone aware object - convert to UTC
65+
date_time = date_time.astimezone(tz=datetime.UTC)
6366
return date_time.strftime("%Y-%m-%d %H:%M:%S.%f")
6467
except Exception:
6568
return ""
6669

6770

6871
def convert_unix_to_utc_datetime(
69-
timestamp: Union[int, float, str]
72+
timestamp: Union[int, float, str],
7073
) -> datetime.datetime:
7174
"""Converts a unix epoch timestamp to UTC datetime.
7275

tests/common/test_utils.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,14 @@ def test_convert_datetime_to_iso(self):
4242
converted = convert_unix_to_utc_datetime(TEST_DATE_EPOCH)
4343
assert convert_datetime_to_iso(converted) == TEST_DATE_ISO
4444

45+
def test_convert_timezone_aware_to_iso(self):
46+
assert (
47+
convert_datetime_to_iso(
48+
datetime.strptime("2024-09-30 11:21:20+0200", "%Y-%m-%d %H:%M:%S%z")
49+
)
50+
== "2024-09-30 09:21:20.000000"
51+
)
52+
4553

4654
class TestHashes:
4755
def test_hash_from_file(self):

0 commit comments

Comments
 (0)