Skip to content

Commit b11b39c

Browse files
committed
fix: convert datetime64[us] to datetime64[ns] for TIMESTAMP and DATETIME columns
1 parent 67df733 commit b11b39c

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

pandas_gbq/gbq.py

+10
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,7 @@ def _finalize_dtypes(
630630
"""
631631
import db_dtypes
632632
import pandas.api.types
633+
import pandas as pd
633634

634635
# If you update this mapping, also update the table at
635636
# `docs/reading.rst`.
@@ -652,6 +653,15 @@ def _finalize_dtypes(
652653
if dtype and pandas.api.types.is_object_dtype(df[name]):
653654
df[name] = df[name].astype(dtype, errors="ignore")
654655

656+
# From pandas 2.0, returns datetime64[us]. Convert to datetime64[ns].
657+
if pd.__version__ >= "2.0.0":
658+
if (
659+
field["type"].upper() in ("DATETIME", "TIMESTAMP")
660+
and pandas.api.types.is_datetime64_dtype(df[name])
661+
and not pandas.api.types.is_datetime64_ns_dtype(df[name])
662+
):
663+
df[name] = df[name].dt.as_unit("ns")
664+
655665
# Ensure any TIMESTAMP columns are tz-aware.
656666
df = pandas_gbq.timestamp.localize_df(df, schema_fields)
657667

tests/unit/test_gbq.py

+23
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,29 @@ def test__bqschema_to_nullsafe_dtypes(type_, expected):
113113
assert result == {"x": expected}
114114

115115

116+
@pytest.mark.parametrize(
117+
("data", "schema_type", "expected"),
118+
[
119+
(
120+
pandas.Timestamp("2017-01-01T12:00:00Z").as_unit("us"),
121+
"TIMESTAMP",
122+
pandas.DatetimeTZDtype(unit="ns", tz="UTC"),
123+
),
124+
(
125+
pandas.Timestamp("2017-01-01T12:00:00").as_unit("us"),
126+
"DATETIME",
127+
numpy.dtype("datetime64[ns]"),
128+
),
129+
],
130+
)
131+
def test__finalize_dtypes(data, schema_type, expected):
132+
result = gbq._finalize_dtypes(
133+
pandas.DataFrame([dict(x=data)]),
134+
[dict(name="x", type=schema_type, mode="NULLABLE")],
135+
)
136+
assert result["x"].dtype == expected
137+
138+
116139
@pytest.mark.parametrize(
117140
["query_or_table", "expected"],
118141
[

0 commit comments

Comments
 (0)