Skip to content

Commit

Permalink
Merge pull request googleapis#2805 from tseaver/1382-bigquery-table-i…
Browse files Browse the repository at this point in the history
…nsert_data-timestamp_strings

Allow timestamp strings in 'Table.insert_data'.
  • Loading branch information
tseaver authored Dec 5, 2016
2 parents 84486b2 + d76ba71 commit 5f04239
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
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

0 comments on commit 5f04239

Please sign in to comment.