Skip to content

Commit 5ce1578

Browse files
author
Jens Larsson
committed
Support parsing DATE columns from Standard SQL tables
Change-Id: Ic979171dfb9d2210334c51a92f8d799cafbff95a
1 parent 92219b8 commit 5ce1578

3 files changed

Lines changed: 32 additions & 0 deletions

File tree

google/cloud/_helpers.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,19 @@ def _millis_from_datetime(value):
379379
return _millis(value)
380380

381381

382+
def _date_from_iso8601_date(value):
383+
"""Convert a ISO8601 date string to native datetime date
384+
385+
:type value: str
386+
:param value: The date string to convert
387+
388+
:rtype: :class:`datetime.date`
389+
:returns: A datetime date object created from the string
390+
391+
"""
392+
return datetime.datetime.strptime(value, '%Y-%m-%d').date()
393+
394+
382395
def _rfc3339_to_datetime(dt_str):
383396
"""Convert a microsecond-precision timetamp to a native datetime.
384397

google/cloud/bigquery/_helpers.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""Shared helper functions for BigQuery API classes."""
1616

1717
from google.cloud._helpers import _datetime_from_microseconds
18+
from google.cloud._helpers import _date_from_iso8601_date
1819

1920

2021
def _not_null(value, field):
@@ -47,6 +48,12 @@ def _datetime_from_json(value, field):
4748
return _datetime_from_microseconds(1e6 * float(value))
4849

4950

51+
def _date_from_json(value, field):
52+
"""Coerce 'value' to a datetime date, if set or not nullable"""
53+
if _not_null(value, field):
54+
return _date_from_iso8601_date(value)
55+
56+
5057
def _record_from_json(value, field):
5158
"""Coerce 'value' to a mapping, if set or not nullable."""
5259
if _not_null(value, field):
@@ -71,6 +78,7 @@ def _string_from_json(value, _):
7178
'FLOAT': _float_from_json,
7279
'BOOLEAN': _bool_from_json,
7380
'TIMESTAMP': _datetime_from_json,
81+
'DATE': _date_from_json,
7482
'RECORD': _record_from_json,
7583
'STRING': _string_from_json,
7684
}

unit_tests/test__helpers.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,17 @@ def test_it(self):
531531
NOW_MICROS = _microseconds_from_datetime(NOW)
532532
self.assertEqual(self._callFUT(NOW_MICROS), NOW)
533533

534+
class Test___date_from_iso8601_date(unittest.TestCase):
535+
536+
def _callFUT(self, value):
537+
from google.cloud._helpers import _date_from_iso8601_date
538+
return _date_from_iso8601_date(value)
539+
540+
def test_todays_date(self):
541+
import datetime
542+
TODAY = datetime.date.today()
543+
self.assertEqual(self._callFUT(TODAY.strftime("%Y-%m-%d")), TODAY)
544+
534545

535546
class Test__rfc3339_to_datetime(unittest.TestCase):
536547

0 commit comments

Comments
 (0)