Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow timestamp strings in 'Table.insert_data'. #2805

Merged
merged 2 commits into from
Dec 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions bigquery/google/cloud/bigquery/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -742,11 +742,11 @@ def insert_data(self,
row_info = {}

for field, value in zip(self._schema, row):
if field.field_type == 'TIMESTAMP' and value is not None:
if field.field_type == 'TIMESTAMP':
# BigQuery stores TIMESTAMP data internally as a
# UNIX timestamp with microsecond precision.
# Specifies the number of seconds since the epoch.
value = _microseconds_from_datetime(value) * 1e-6
value = _convert_timestamp(value)
row_info[field.name] = value

info = {'json': row_info}
Expand Down Expand Up @@ -1129,3 +1129,10 @@ class _UrlBuilder(object):
def __init__(self):
self.query_params = {}
self._relative_path = ''


def _convert_timestamp(value):
"""Helper for :meth:`Table.insert_data`."""
if isinstance(value, datetime.datetime):
value = _microseconds_from_datetime(value) * 1e-6
return value
9 changes: 5 additions & 4 deletions bigquery/unit_tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,7 @@ def test_insert_data_wo_schema(self):
def test_insert_data_w_bound_client(self):
import datetime
from google.cloud._helpers import UTC
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud._helpers import _microseconds_from_datetime
from google.cloud.bigquery.table import SchemaField

Expand All @@ -1313,16 +1314,16 @@ def test_insert_data_w_bound_client(self):
table = self._make_one(self.TABLE_NAME, dataset=dataset,
schema=[full_name, age, joined])
ROWS = [
('Phred Phlyntstone', 32, WHEN),
('Phred Phlyntstone', 32, _datetime_to_rfc3339(WHEN)),
('Bharney Rhubble', 33, WHEN + datetime.timedelta(seconds=1)),
('Wylma Phlyntstone', 29, WHEN + datetime.timedelta(seconds=2)),
('Bhettye Rhubble', 27, None),
]

def _row_data(row):
joined = None
if row[2] is not None:
joined = _microseconds_from_datetime(row[2]) * 1e-6
joined = row[2]
if isinstance(row[2], datetime.datetime):
joined = _microseconds_from_datetime(joined) * 1e-6
return {'full_name': row[0],
'age': row[1],
'joined': joined}
Expand Down