diff --git a/core/google/cloud/_helpers.py b/core/google/cloud/_helpers.py index 09a2e3f4ff3f..c6def05721a8 100644 --- a/core/google/cloud/_helpers.py +++ b/core/google/cloud/_helpers.py @@ -43,6 +43,8 @@ _NOW = datetime.datetime.utcnow # To be replaced by tests. _RFC3339_MICROS = '%Y-%m-%dT%H:%M:%S.%fZ' _RFC3339_NO_FRACTION = '%Y-%m-%dT%H:%M:%S' +_TIMEONLY_W_MICROS = '%H:%M:%S.%f' +_TIMEONLY_NO_FRACTION = '%H:%M:%S' # datetime.strptime cannot handle nanosecond precision: parse w/ regex _RFC3339_NANOS = re.compile(r""" (?P @@ -256,9 +258,15 @@ def _time_from_iso8601_time_naive(value): :rtype: :class:`datetime.time` :returns: A datetime time object created from the string - + :raises ValueError: if the value does not match a known format. """ - return datetime.datetime.strptime(value, '%H:%M:%S').time() + if len(value) == 8: # HH:MM:SS + fmt = _TIMEONLY_NO_FRACTION + elif len(value) == 15: # HH:MM:SS.micros + fmt = _TIMEONLY_W_MICROS + else: + raise ValueError("Unknown time format: {}".format(value)) + return datetime.datetime.strptime(value, fmt).time() def _rfc3339_to_datetime(dt_str): diff --git a/core/tests/unit/test__helpers.py b/core/tests/unit/test__helpers.py index a17228b4556f..2da56fd12ca2 100644 --- a/core/tests/unit/test__helpers.py +++ b/core/tests/unit/test__helpers.py @@ -298,6 +298,16 @@ def test_todays_date(self): WHEN = datetime.time(12, 9, 42) self.assertEqual(self._call_fut(("12:09:42")), WHEN) + def test_w_microseconds(self): + import datetime + + WHEN = datetime.time(12, 9, 42, 123456) + self.assertEqual(self._call_fut(("12:09:42.123456")), WHEN) + + def test_w_millis_fail(self): + with self.assertRaises(ValueError): + self._call_fut("12:09:42.123") + class Test__rfc3339_to_datetime(unittest.TestCase):