Skip to content

Commit

Permalink
Fix conversion of backend-generated timestamp values.
Browse files Browse the repository at this point in the history
BQ returns them as strings, representing UNIX timestamp seconds-since-epoch
to microsecond precision.

Fixes #1125.
  • Loading branch information
tseaver committed Sep 10, 2015
1 parent 51427ec commit e004a76
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
6 changes: 4 additions & 2 deletions gcloud/bigquery/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import six

from gcloud._helpers import UTC
from gcloud._helpers import _datetime_from_microseconds
from gcloud._helpers import _millis_from_datetime
from gcloud.exceptions import NotFound
Expand Down Expand Up @@ -761,8 +762,9 @@ def _bool_from_json(value, field):

def _datetime_from_json(value, field):
if _not_null(value, field):
# Field value will be in milliseconds.
return _datetime_from_microseconds(1000.0 * float(value))
# value will be a float in seconds, to microsecond precision, in UTC.
stamp = datetime.datetime.utcfromtimestamp(float(value))
return stamp.replace(tzinfo=UTC)


def _record_from_json(value, field):
Expand Down
13 changes: 9 additions & 4 deletions gcloud/bigquery/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,6 @@ def test_fetch_data_w_bound_client(self):
import datetime
from gcloud._helpers import UTC
from gcloud.bigquery.table import SchemaField
from gcloud._helpers import _millis_from_datetime

PATH = 'projects/%s/datasets/%s/tables/%s/data' % (
self.PROJECT, self.DS_NAME, self.TABLE_NAME)
Expand All @@ -835,24 +834,29 @@ def test_fetch_data_w_bound_client(self):
WHEN_2 = WHEN + datetime.timedelta(seconds=2)
ROWS = 1234
TOKEN = 'TOKEN'

def _bigquery_timestamp_float_repr(ts_float):
# Preserve microsecond precision for E+09 timestamps
return '%0.15E' % (ts_float,)

DATA = {
'totalRows': ROWS,
'pageToken': TOKEN,
'rows': [
{'f': [
{'v': 'Phred Phlyntstone'},
{'v': '32'},
{'v': _millis_from_datetime(WHEN)},
{'v': _bigquery_timestamp_float_repr(WHEN_TS)},
]},
{'f': [
{'v': 'Bharney Rhubble'},
{'v': '33'},
{'v': _millis_from_datetime(WHEN_1)},
{'v': _bigquery_timestamp_float_repr(WHEN_TS + 1)},
]},
{'f': [
{'v': 'Wylma Phlyntstone'},
{'v': '29'},
{'v': _millis_from_datetime(WHEN_2)},
{'v': _bigquery_timestamp_float_repr(WHEN_TS + 2)},
]},
{'f': [
{'v': 'Bhettye Rhubble'},
Expand All @@ -861,6 +865,7 @@ def test_fetch_data_w_bound_client(self):
]},
]
}

conn = _Connection(DATA)
client = _Client(project=self.PROJECT, connection=conn)
dataset = _Dataset(client)
Expand Down

0 comments on commit e004a76

Please sign in to comment.