Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert timezone-aware datetimes automatically to UTC #485

Merged
merged 1 commit into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions mvt/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,23 @@ def convert_chrometime_to_datetime(timestamp: int) -> datetime.datetime:
def convert_datetime_to_iso(date_time: datetime.datetime) -> str:
"""Converts datetime to ISO string.

:param datetime: datetime.
:param datetime: datetime, naive or timezone aware
:type datetime: datetime.datetime
:returns: ISO datetime string in YYYY-mm-dd HH:MM:SS.ms format.
:rtype: str

"""
try:
if date_time.tzinfo:
# Timezone aware object - convert to UTC
date_time = date_time.astimezone(tz=datetime.UTC)
return date_time.strftime("%Y-%m-%d %H:%M:%S.%f")
except Exception:
return ""


def convert_unix_to_utc_datetime(
timestamp: Union[int, float, str]
timestamp: Union[int, float, str],
) -> datetime.datetime:
"""Converts a unix epoch timestamp to UTC datetime.

Expand Down
8 changes: 8 additions & 0 deletions tests/common/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ def test_convert_datetime_to_iso(self):
converted = convert_unix_to_utc_datetime(TEST_DATE_EPOCH)
assert convert_datetime_to_iso(converted) == TEST_DATE_ISO

def test_convert_timezone_aware_to_iso(self):
assert (
convert_datetime_to_iso(
datetime.strptime("2024-09-30 11:21:20+0200", "%Y-%m-%d %H:%M:%S%z")
)
== "2024-09-30 09:21:20.000000"
)


class TestHashes:
def test_hash_from_file(self):
Expand Down
Loading