diff --git a/customerio/client_base.py b/customerio/client_base.py index e333b08..db5b70a 100644 --- a/customerio/client_base.py +++ b/customerio/client_base.py @@ -123,6 +123,8 @@ def _sanitize_value(self, value): return value def _datetime_to_timestamp(self, dt): + if dt.tzinfo is not None: + return int(dt.astimezone(timezone.utc).timestamp()) return int(dt.replace(tzinfo=timezone.utc).timestamp()) def _stringify_list(self, customer_ids): diff --git a/tests/test_customerio.py b/tests/test_customerio.py index 1995e79..e175ad7 100644 --- a/tests/test_customerio.py +++ b/tests/test_customerio.py @@ -1,7 +1,7 @@ import json import socket import unittest -from datetime import datetime +from datetime import datetime, timedelta, timezone from functools import partial import urllib3 @@ -562,12 +562,24 @@ def test_unsuppress_call(self): self.cio.unsuppress(None) def test_sanitize(self): - from datetime import timezone - data_in = dict(dt=datetime(2009, 2, 13, 23, 31, 30, 0, timezone.utc)) data_out = self.cio._sanitize(data_in) self.assertEqual(data_out, dict(dt=1234567890)) + def test_sanitize_naive_datetime(self): + """Naive datetimes are assumed UTC (backward compatible).""" + data_in = dict(dt=datetime(2009, 2, 13, 23, 31, 30)) + data_out = self.cio._sanitize(data_in) + self.assertEqual(data_out, dict(dt=1234567890)) + + def test_sanitize_aware_non_utc_datetime(self): + """Tz-aware non-UTC datetimes are converted, not silently replaced.""" + # 2009-02-13 18:31:30 at UTC-5 is 2009-02-13 23:31:30 UTC + tz_minus_5 = timezone(timedelta(hours=-5)) + data_in = dict(dt=datetime(2009, 2, 13, 18, 31, 30, 0, tz_minus_5)) + data_out = self.cio._sanitize(data_in) + self.assertEqual(data_out, dict(dt=1234567890)) + def test_ids_are_encoded_in_url(self): self.cio.http.hooks = dict( response=partial(