This repository was archived by the owner on Mar 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 325
feat: default to DATETIME type when loading timezone-naive datetimes from Pandas #1061
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,7 +15,9 @@ | |
| """Shared helper functions for connecting BigQuery and pandas.""" | ||
|
|
||
| import concurrent.futures | ||
| from datetime import datetime | ||
| import functools | ||
| from itertools import islice | ||
| import logging | ||
| import queue | ||
| import warnings | ||
|
|
@@ -85,9 +87,7 @@ def _to_wkb(v): | |
| _PANDAS_DTYPE_TO_BQ = { | ||
| "bool": "BOOLEAN", | ||
| "datetime64[ns, UTC]": "TIMESTAMP", | ||
| # TODO: Update to DATETIME in V3 | ||
| # https://github.com/googleapis/python-bigquery/issues/985 | ||
| "datetime64[ns]": "TIMESTAMP", | ||
| "datetime64[ns]": "DATETIME", | ||
| "float32": "FLOAT", | ||
| "float64": "FLOAT", | ||
| "int8": "INTEGER", | ||
|
|
@@ -379,6 +379,36 @@ def _first_valid(series): | |
| return series.at[first_valid_index] | ||
|
|
||
|
|
||
| def _first_array_valid(series): | ||
| """Return the first "meaningful" element from the array series. | ||
|
|
||
| Here, "meaningful" means the first non-None element in one of the arrays that can | ||
| be used for type detextion. | ||
| """ | ||
| first_valid_index = series.first_valid_index() | ||
| if first_valid_index is None: | ||
| return None | ||
|
|
||
| valid_array = series.at[first_valid_index] | ||
| valid_item = next((item for item in valid_array if not pandas.isna(item)), None) | ||
|
|
||
| if valid_item is not None: | ||
| return valid_item | ||
|
|
||
| # Valid item is None because all items in the "valid" array are invalid. Try | ||
| # to find a true valid array manually. | ||
| for array in islice(series, first_valid_index + 1, None): | ||
| try: | ||
| array_iter = iter(array) | ||
| except TypeError: | ||
| continue # Not an array, apparently, e.g. None, thus skip. | ||
| valid_item = next((item for item in array_iter if not pandas.isna(item)), None) | ||
| if valid_item is not None: | ||
| break | ||
|
|
||
| return valid_item | ||
|
|
||
|
|
||
| def dataframe_to_bq_schema(dataframe, bq_schema): | ||
| """Convert a pandas DataFrame schema to a BigQuery schema. | ||
|
|
||
|
|
@@ -482,6 +512,19 @@ def augment_schema(dataframe, current_bq_schema): | |
| # `pyarrow.ListType` | ||
| detected_mode = "REPEATED" | ||
| detected_type = ARROW_SCALAR_IDS_TO_BQ.get(arrow_table.values.type.id) | ||
|
|
||
| # For timezone-naive datetimes, pyarrow assumes the UTC timezone and adds | ||
| # it to such datetimes, causing them to be recognized as TIMESTAMP type. | ||
| # We thus additionally check the actual data to see if we need to overrule | ||
| # that and choose DATETIME instead. | ||
| # Note that this should only be needed for datetime values inside a list, | ||
| # since scalar datetime values have a proper Pandas dtype that allows | ||
| # distinguishing between timezone-naive and timezone-aware values before | ||
| # even requiring the additional schema augment logic in this method. | ||
| if detected_type == "TIMESTAMP": | ||
| valid_item = _first_array_valid(dataframe[field.name]) | ||
| if isinstance(valid_item, datetime) and valid_item.tzinfo is None: | ||
| detected_type = "DATETIME" | ||
|
Comment on lines
+524
to
+527
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I was thinking of doing this check for all detected TIMESTAMP values, but it turned out it's only necessary for datetimes inside an array, because that's when we need to use For datetime values outside of arrays, we can already distinguish between naive and aware ones based on Pandas dtypes, meaning that we do not even enter |
||
| else: | ||
| detected_mode = field.mode | ||
| detected_type = ARROW_SCALAR_IDS_TO_BQ.get(arrow_table.type.id) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was not sure if slicing the series results in an unnecessary copy (Pandas docs say it's context-dependent), thus played it safe and just used
islice.