Skip to content

Commit 5cfaa89

Browse files
committed
Fix datetime conversion issue on python < 3.6
1 parent 0b4b589 commit 5cfaa89

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

tests/stores/test_azure_log_analytics.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from datetime import datetime
12
from dateutil import parser
23
from django.test import SimpleTestCase
34
from zentral.core.stores.backends.azure_log_analytics import datetime_to_iso8601z_truncated_to_milliseconds
@@ -25,3 +26,9 @@ def test_microseconds_to_milliseconds(self):
2526
("2019-01-12T11:11:11.000999+00:00", "2019-01-12T11:11:11.001Z"),
2627
("2019-01-12T11:11:11.000234+00:00", "2019-01-12T11:11:11Z"),
2728
))
29+
30+
def test_naive_datetime(self):
31+
self.assertEqual(
32+
datetime_to_iso8601z_truncated_to_milliseconds(datetime(2019, 1, 1, 0, 0, 0).replace(tzinfo=None)),
33+
"2019-01-01T00:00:00Z"
34+
)

zentral/core/stores/backends/azure_log_analytics.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,12 @@ def datetime_to_iso8601z_truncated_to_milliseconds(dt):
2525
else:
2626
dt = dt.replace(microsecond=1000 * dt_millisecond)
2727

28-
# convert created at to UTC, remove the TZ info (naive datetime), convert to isoformat
29-
dt_iso = dt.astimezone(pytz.utc).replace(tzinfo=None).isoformat()
28+
# convert to UTC only if not naive (python<3.6)
29+
if dt.utcoffset() is not None:
30+
dt = dt.astimezone(pytz.utc)
31+
32+
# ensure naive, convert to isoformat
33+
dt_iso = dt.replace(tzinfo=None).isoformat()
3034

3135
# truncate the microseconds in isoformat if necessary
3236
if "." in dt_iso:

0 commit comments

Comments
 (0)