Skip to content

Commit

Permalink
Support parsing DATE columns from Standard SQL tables
Browse files Browse the repository at this point in the history
Change-Id: Ic979171dfb9d2210334c51a92f8d799cafbff95a
  • Loading branch information
Jens Larsson committed Sep 8, 2016
1 parent 92219b8 commit 5ce1578
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions google/cloud/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,19 @@ def _millis_from_datetime(value):
return _millis(value)


def _date_from_iso8601_date(value):
"""Convert a ISO8601 date string to native datetime date
:type value: str
:param value: The date string to convert
:rtype: :class:`datetime.date`
:returns: A datetime date object created from the string
"""
return datetime.datetime.strptime(value, '%Y-%m-%d').date()


def _rfc3339_to_datetime(dt_str):
"""Convert a microsecond-precision timetamp to a native datetime.
Expand Down
8 changes: 8 additions & 0 deletions google/cloud/bigquery/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""Shared helper functions for BigQuery API classes."""

from google.cloud._helpers import _datetime_from_microseconds
from google.cloud._helpers import _date_from_iso8601_date


def _not_null(value, field):
Expand Down Expand Up @@ -47,6 +48,12 @@ def _datetime_from_json(value, field):
return _datetime_from_microseconds(1e6 * float(value))


def _date_from_json(value, field):
"""Coerce 'value' to a datetime date, if set or not nullable"""
if _not_null(value, field):
return _date_from_iso8601_date(value)


def _record_from_json(value, field):
"""Coerce 'value' to a mapping, if set or not nullable."""
if _not_null(value, field):
Expand All @@ -71,6 +78,7 @@ def _string_from_json(value, _):
'FLOAT': _float_from_json,
'BOOLEAN': _bool_from_json,
'TIMESTAMP': _datetime_from_json,
'DATE': _date_from_json,
'RECORD': _record_from_json,
'STRING': _string_from_json,
}
Expand Down
11 changes: 11 additions & 0 deletions unit_tests/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,17 @@ def test_it(self):
NOW_MICROS = _microseconds_from_datetime(NOW)
self.assertEqual(self._callFUT(NOW_MICROS), NOW)

class Test___date_from_iso8601_date(unittest.TestCase):

def _callFUT(self, value):
from google.cloud._helpers import _date_from_iso8601_date
return _date_from_iso8601_date(value)

def test_todays_date(self):
import datetime
TODAY = datetime.date.today()
self.assertEqual(self._callFUT(TODAY.strftime("%Y-%m-%d")), TODAY)


class Test__rfc3339_to_datetime(unittest.TestCase):

Expand Down

0 comments on commit 5ce1578

Please sign in to comment.