Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

fix(python): send DataFrame datetimes without a UTC offset and NaN/NaT as null (#3838)

Arthur0043b242e738
diff --git a/bindings/python/keplergl/serializers.py b/bindings/python/keplergl/serializers.py
index 0905f40ec..96b515318 100644
--- a/bindings/python/keplergl/serializers.py
+++ b/bindings/python/keplergl/serializers.py
@@ -90,6 +90,20 @@ def serialize_dataframe(df: pd.DataFrame, name: str, use_arrow: bool = False) ->
columns = df.columns.tolist()
rows = df.values.tolist()
+ # Jupyter adds the kernel's UTC offset to naive datetimes, which shifts them
+ # in the map, so send datetime columns as ISO strings instead
+ for c, dtype in enumerate(df.dtypes):
+ if pd.api.types.is_datetime64_any_dtype(dtype):
+ # Series.dt.strftime fails on Arrow-backed timestamps, so format each value
+ times = [
+ None if pd.isna(t) else t.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
+ for t in df.iloc[:, c]
+ ]
+ for row, time in zip(rows, times):
+ row[c] = time
+ # NaN and NaT are not valid JSON, so send them as null
+ for r, c in zip(*df.isna().to_numpy().nonzero()):
+ rows[r][c] = None
_debug(f"serialize_dataframe: {len(columns)} columns, {len(rows)} rows")
_debug(f" columns: {columns}")
_debug(f" first row: {rows[0] if rows else 'empty'}")
diff --git a/bindings/python/tests/test_serializers.py b/bindings/python/tests/test_serializers.py
index 75e18025d..85826bc41 100644
--- a/bindings/python/tests/test_serializers.py
+++ b/bindings/python/tests/test_serializers.py
@@ -489,16 +489,73 @@ class TestEdgeCases:
def test_serialize_dataframe_with_nan(self):
"""NaN values in a DataFrame should not raise during serialization,
and the row containing NaN should be preserved (not dropped)."""
- import math
df = pd.DataFrame({'a': [1.0, float('nan'), 3.0]})
result = serialize_dataset(df, "nan_test")
assert result["format"] == "df"
rows = result["data"]["data"]
assert len(rows) == 3
assert rows[0][0] == pytest.approx(1.0)
- assert math.isnan(rows[1][0])
+ assert rows[1][0] is None
assert rows[2][0] == pytest.approx(3.0)
+ def test_serialize_dataframe_datetime_without_offset(self):
+ """Naive datetimes must be sent as plain ISO strings, since an offset
+ added by the kernel's time zone would shift them in the map."""
+ import json
+ df = pd.DataFrame({
+ 't': pd.to_datetime(['2024-01-01 00:00:00.000', '2024-06-01 12:30:00.500']),
+ 'v': [1, 2],
+ })
+ result = serialize_dataset(df, "dt_test")
+ rows = result["data"]["data"]
+ assert rows[0] == ['2024-01-01T00:00:00.000000', 1]
+ assert rows[1] == ['2024-06-01T12:30:00.500000', 2]
+ json.dumps(result, allow_nan=False)
+
+ def test_serialize_dataframe_datetime_only(self):
+ """A DataFrame with only datetime columns should be sent as ISO strings."""
+ df = pd.DataFrame({'t': pd.to_datetime(['2024-01-01 00:00:00'])})
+ rows = serialize_dataset(df, "dt_only")["data"]["data"]
+ assert rows == [['2024-01-01T00:00:00.000000']]
+
+ def test_serialize_dataframe_datetime_with_nat(self):
+ """NaT should be sent as null instead of failing in JSON serialization."""
+ import json
+ df = pd.DataFrame({
+ 't': pd.to_datetime(['2024-01-01 00:00:00', None]),
+ 'v': [1.0, float('nan')],
+ })
+ result = serialize_dataset(df, "nat_test")
+ rows = result["data"]["data"]
+ assert rows == [['2024-01-01T00:00:00.000000', 1.0], [None, None]]
+ json.dumps(result, allow_nan=False)
+
+ def test_serialize_dataframe_datetime_with_timezone(self):
+ """Timezone-aware datetimes keep their UTC offset."""
+ df = pd.DataFrame({
+ 't': pd.to_datetime(['2024-01-01 00:00:00']).tz_localize('Asia/Taipei'),
+ })
+ rows = serialize_dataset(df, "tz_test")["data"]["data"]
+ assert rows == [['2024-01-01T00:00:00.000000+0800']]
+
+ @pytest.mark.parametrize("tz, offset", [(None, ""), ("Asia/Taipei", "+0800")])
+ def test_serialize_dataframe_datetime_arrow_dtype(self, tz, offset):
+ """Arrow-backed timestamp columns are formatted like numpy ones, with
+ NaT sent as null."""
+ import json
+ pa = pytest.importorskip("pyarrow")
+ t = pd.to_datetime(['2024-01-01 00:00:00.000', '2024-06-01 12:30:00.500', None])
+ if tz:
+ t = t.tz_localize(tz)
+ df = pd.DataFrame({'t': pd.Series(t).astype(pd.ArrowDtype(pa.timestamp('us', tz=tz)))})
+ result = serialize_dataset(df, "arrow_dt_test")
+ assert result["data"]["data"] == [
+ ['2024-01-01T00:00:00.000000' + offset],
+ ['2024-06-01T12:30:00.500000' + offset],
+ [None],
+ ]
+ json.dumps(result, allow_nan=False)
+
def test_serialize_dataframe_arrow_with_nan(self):
"""Arrow serialization of a DataFrame containing NaN should not raise,
and NaN should round-trip as null in Arrow."""