File tree 2 files changed +33
-0
lines changed
2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -630,6 +630,7 @@ def _finalize_dtypes(
630
630
"""
631
631
import db_dtypes
632
632
import pandas .api .types
633
+ import pandas as pd
633
634
634
635
# If you update this mapping, also update the table at
635
636
# `docs/reading.rst`.
@@ -652,6 +653,15 @@ def _finalize_dtypes(
652
653
if dtype and pandas .api .types .is_object_dtype (df [name ]):
653
654
df [name ] = df [name ].astype (dtype , errors = "ignore" )
654
655
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
+
655
665
# Ensure any TIMESTAMP columns are tz-aware.
656
666
df = pandas_gbq .timestamp .localize_df (df , schema_fields )
657
667
Original file line number Diff line number Diff line change @@ -113,6 +113,29 @@ def test__bqschema_to_nullsafe_dtypes(type_, expected):
113
113
assert result == {"x" : expected }
114
114
115
115
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
+
116
139
@pytest .mark .parametrize (
117
140
["query_or_table" , "expected" ],
118
141
[
You can’t perform that action at this time.
0 commit comments