From 440602ef344a1e4e93cbb65f03d0763e87bf2d9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=BCrker=20Ziya=20Ercin?= <51151883+tzercin@users.noreply.github.com> Date: Sun, 15 Feb 2026 18:36:18 +0300 Subject: [PATCH] fix(utils): datetime_to_epoch function is fixed to timezone aware epoch (#37979) --- superset/utils/dates.py | 2 +- tests/unit_tests/utils/json_tests.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/superset/utils/dates.py b/superset/utils/dates.py index b2b422a1f09..b240bf5ab40 100644 --- a/superset/utils/dates.py +++ b/superset/utils/dates.py @@ -24,7 +24,7 @@ EPOCH = datetime(1970, 1, 1) def datetime_to_epoch(dttm: datetime) -> float: """Convert datetime to milliseconds to epoch""" if dttm.tzinfo: - dttm = dttm.replace(tzinfo=pytz.utc) + dttm = dttm.astimezone(pytz.utc) epoch_with_tz = pytz.utc.localize(EPOCH) return (dttm - epoch_with_tz).total_seconds() * 1000 return (dttm - EPOCH).total_seconds() * 1000 diff --git a/tests/unit_tests/utils/json_tests.py b/tests/unit_tests/utils/json_tests.py index 89c0a5a1657..957ce5e251a 100644 --- a/tests/unit_tests/utils/json_tests.py +++ b/tests/unit_tests/utils/json_tests.py @@ -24,6 +24,7 @@ from unittest.mock import MagicMock import numpy as np import pandas as pd import pytest +import pytz from superset.utils import json from superset.utils.core import ( @@ -252,6 +253,11 @@ def test_json_int_dttm_ser(): assert json.json_int_dttm_ser(datetime(1970, 1, 1)) == 0 assert json.json_int_dttm_ser(date(1970, 1, 1)) == 0 assert json.json_int_dttm_ser(dttm + timedelta(milliseconds=1)) == (ts + 1) + + # Timezone-aware datetime should preserve the absolute instant. + # 2020-01-01 00:00:00+08:00 == 2019-12-31 16:00:00Z + dttm_tz = datetime(2020, 1, 1, tzinfo=pytz.FixedOffset(8 * 60)) + assert json.json_int_dttm_ser(dttm_tz) == 1577808000000.0 assert json.json_int_dttm_ser(np.int64(1)) == 1 with pytest.raises(TypeError):