From 090dc1ef4e2e2abdece921f53791abc35489cd7b Mon Sep 17 00:00:00 2001 From: dagemawinegash Date: Sat, 5 Dec 2026 13:07:28 +0200 Subject: [PATCH] Preserve nanosecond precision for timezone-aware pandas timestamps --- src/numpy/numpy_scan.cpp | 14 +++++--------- src/numpy/type.cpp | 2 +- src/pyresult.cpp | 2 +- tests/fast/pandas/test_pandas_scan_bind_reads.py | 2 +- tests/fast/pandas/test_pandas_timestamp.py | 14 ++++++++++++++ tests/fast/pandas/test_timestamp.py | 5 ++--- 6 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/numpy/numpy_scan.cpp b/src/numpy/numpy_scan.cpp index 6104838ec..579e33a2d 100644 --- a/src/numpy/numpy_scan.cpp +++ b/src/numpy/numpy_scan.cpp @@ -1325,12 +1325,11 @@ void NumpyScan::Scan(ClientContext &context, PandasColumnBindData &bind_data, id switch (bind_data.numpy_type.type) { case NumpyNullableType::DATETIME_NS: - if (bind_data.numpy_type.has_timezone) { - // Our timezone type is US, so we need to convert from NS to US - convert_func = Timestamp::FromEpochNanoSeconds; - } else { - convert_func = Timestamp::FromEpochMicroSeconds; - } + case NumpyNullableType::DATETIME_US: + // The bound timestamp type stores the same unit as the input. + convert_func = [](int64_t value) { + return timestamp_t(value); + }; break; case NumpyNullableType::DATETIME_MS: if (bind_data.numpy_type.has_timezone) { @@ -1340,9 +1339,6 @@ void NumpyScan::Scan(ClientContext &context, PandasColumnBindData &bind_data, id convert_func = Timestamp::FromEpochMicroSeconds; } break; - case NumpyNullableType::DATETIME_US: - convert_func = Timestamp::FromEpochMicroSeconds; - break; case NumpyNullableType::DATETIME_S: if (bind_data.numpy_type.has_timezone) { // Our timezone type is US, so we need to convert from S to US diff --git a/src/numpy/type.cpp b/src/numpy/type.cpp index 71484ae7f..955727169 100644 --- a/src/numpy/type.cpp +++ b/src/numpy/type.cpp @@ -165,7 +165,7 @@ LogicalType NumpyToLogicalType(const NumpyType &col_type) { } case NumpyNullableType::DATETIME_NS: { if (col_type.has_timezone) { - return LogicalType::TIMESTAMP_TZ; + return LogicalType::TIMESTAMP_TZ_NS; } return LogicalType::TIMESTAMP_NS; } diff --git a/src/pyresult.cpp b/src/pyresult.cpp index e1cdd32b2..e4e8c4a9d 100644 --- a/src/pyresult.cpp +++ b/src/pyresult.cpp @@ -321,7 +321,7 @@ void DuckDBPyResult::ConvertDateTimeTypes(PandasDataFrame &df, bool date_as_obje auto &types = GetTypes(); for (idx_t i = 0; i < types.size(); i++) { - if (types[i] == LogicalType::TIMESTAMP_TZ) { + if (types[i] == LogicalType::TIMESTAMP_TZ || types[i] == LogicalType::TIMESTAMP_TZ_NS) { // first localize to UTC then convert to timezone_config auto utc_local = df[names[i].c_str()].attr("dt").attr("tz_localize")("UTC"); auto new_value = utc_local.attr("dt").attr("tz_convert")(GetClientProperties().time_zone); diff --git a/tests/fast/pandas/test_pandas_scan_bind_reads.py b/tests/fast/pandas/test_pandas_scan_bind_reads.py index 0d46a9c22..89156bfab 100644 --- a/tests/fast/pandas/test_pandas_scan_bind_reads.py +++ b/tests/fast/pandas/test_pandas_scan_bind_reads.py @@ -169,7 +169,7 @@ class ColumnCase(NamedTuple): ), "datetime_tz": ColumnCase( lambda: pd.Series(_TZ_TIMES), - "TIMESTAMP WITH TIME ZONE", + "TIMESTAMPTZ_NS" if _TZ_TIMES.dtype.unit == "ns" else "TIMESTAMP WITH TIME ZONE", [timestamp.to_pydatetime() for timestamp in _TZ_TIMES], ), "datetime_naive": ColumnCase( diff --git a/tests/fast/pandas/test_pandas_timestamp.py b/tests/fast/pandas/test_pandas_timestamp.py index 30aea04cf..e58bc4e89 100644 --- a/tests/fast/pandas/test_pandas_timestamp.py +++ b/tests/fast/pandas/test_pandas_timestamp.py @@ -24,6 +24,20 @@ def test_run_pandas_with_tz(timezone): assert duck_df["timestamp"][0] == df["timestamp"][0] +@pytest.mark.parametrize("timezone", ["UTC", "Asia/Kathmandu"]) +def test_timezone_aware_nanosecond_timestamps(duckdb_cursor, timezone): + timestamps = pandas.to_datetime([-1, 100, 900, None], unit="ns", utc=True).tz_convert(timezone) + frame = pandas.DataFrame({"ts": timestamps}) + duckdb_cursor.execute(f"SET TimeZone = '{timezone}'") + duckdb_cursor.register("timestamps", frame) + + rows = duckdb_cursor.execute("SELECT typeof(ts), epoch_ns(ts) FROM timestamps ORDER BY ts NULLS LAST").fetchall() + + assert rows == [("TIMESTAMPTZ_NS", -1), ("TIMESTAMPTZ_NS", 100), ("TIMESTAMPTZ_NS", 900), ("TIMESTAMPTZ_NS", None)] + result = duckdb_cursor.sql("SELECT ts FROM timestamps ORDER BY ts NULLS LAST").df() + pandas.testing.assert_frame_equal(result, frame) + + def test_timestamp_conversion(duckdb_cursor): tzinfo = pandas.Timestamp("2024-01-01 00:00:00+0100", tz="Europe/Copenhagen").tzinfo ts_df = pandas.DataFrame( # noqa: F841 diff --git a/tests/fast/pandas/test_timestamp.py b/tests/fast/pandas/test_timestamp.py index 57510b499..4f9095333 100644 --- a/tests/fast/pandas/test_timestamp.py +++ b/tests/fast/pandas/test_timestamp.py @@ -24,7 +24,8 @@ def test_timestamp_types_roundtrip(self, unit): def test_timestamp_timezone_roundtrip(self, unit): if pandas_2_or_higher(): dtype = pd.core.dtypes.dtypes.DatetimeTZDtype(unit=unit, tz="UTC") - expected_dtype = pd.core.dtypes.dtypes.DatetimeTZDtype(unit="us", tz="UTC") + expected_unit = "ns" if unit == "ns" else "us" + expected_dtype = pd.core.dtypes.dtypes.DatetimeTZDtype(unit=expected_unit, tz="UTC") else: # Older versions of pandas only support 'ns' as timezone unit expected_dtype = pd.core.dtypes.dtypes.DatetimeTZDtype(unit="ns", tz="UTC") @@ -40,8 +41,6 @@ def test_timestamp_timezone_roundtrip(self, unit): } df = pd.DataFrame(data=d) - # Our timezone aware type is in US (microseconds), when we scan a timestamp column that isn't US and has - # timezone info, we convert the time unit to US expected = pd.DataFrame(data=d, dtype=expected_dtype) df_from_duck = conn.from_df(df).df() assert df_from_duck.equals(expected)