fix(utils): datetime_to_epoch function is fixed to timezone aware epoch (#37979)

This commit is contained in:
Türker Ziya Ercin
2026-02-15 18:36:18 +03:00
committed by GitHub
parent cbf153845e
commit 440602ef34
2 changed files with 7 additions and 1 deletions

View File

@@ -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

View File

@@ -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):