Skip to content

Commit dfdad0e

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

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

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: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,18 @@ def test_it(self):
532532
self.assertEqual(self._callFUT(NOW_MICROS), NOW)
533533

534534

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

537549
def _callFUT(self, dt_str):

0 commit comments

Comments
 (0)