Skip to content

Commit

Permalink
Fix datetime conversion issue on python < 3.6
Browse files Browse the repository at this point in the history
  • Loading branch information
np5 committed Sep 27, 2019
1 parent 0b4b589 commit 5cfaa89
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
7 changes: 7 additions & 0 deletions tests/stores/test_azure_log_analytics.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import datetime
from dateutil import parser
from django.test import SimpleTestCase
from zentral.core.stores.backends.azure_log_analytics import datetime_to_iso8601z_truncated_to_milliseconds
Expand Down Expand Up @@ -25,3 +26,9 @@ def test_microseconds_to_milliseconds(self):
("2019-01-12T11:11:11.000999+00:00", "2019-01-12T11:11:11.001Z"),
("2019-01-12T11:11:11.000234+00:00", "2019-01-12T11:11:11Z"),
))

def test_naive_datetime(self):
self.assertEqual(
datetime_to_iso8601z_truncated_to_milliseconds(datetime(2019, 1, 1, 0, 0, 0).replace(tzinfo=None)),
"2019-01-01T00:00:00Z"
)
8 changes: 6 additions & 2 deletions zentral/core/stores/backends/azure_log_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@ def datetime_to_iso8601z_truncated_to_milliseconds(dt):
else:
dt = dt.replace(microsecond=1000 * dt_millisecond)

# convert created at to UTC, remove the TZ info (naive datetime), convert to isoformat
dt_iso = dt.astimezone(pytz.utc).replace(tzinfo=None).isoformat()
# convert to UTC only if not naive (python<3.6)
if dt.utcoffset() is not None:
dt = dt.astimezone(pytz.utc)

# ensure naive, convert to isoformat
dt_iso = dt.replace(tzinfo=None).isoformat()

# truncate the microseconds in isoformat if necessary
if "." in dt_iso:
Expand Down

0 comments on commit 5cfaa89

Please sign in to comment.