Skip to content

Commit 06e860a

Browse files
authored
Fix '_time_from_iso8601_time_naive' for values with micros. (#5756)
Closes #5750.
1 parent 0f54a97 commit 06e860a

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

core/google/cloud/_helpers.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@
4343
_NOW = datetime.datetime.utcnow # To be replaced by tests.
4444
_RFC3339_MICROS = '%Y-%m-%dT%H:%M:%S.%fZ'
4545
_RFC3339_NO_FRACTION = '%Y-%m-%dT%H:%M:%S'
46+
_TIMEONLY_W_MICROS = '%H:%M:%S.%f'
47+
_TIMEONLY_NO_FRACTION = '%H:%M:%S'
4648
# datetime.strptime cannot handle nanosecond precision: parse w/ regex
4749
_RFC3339_NANOS = re.compile(r"""
4850
(?P<no_fraction>
@@ -256,9 +258,15 @@ def _time_from_iso8601_time_naive(value):
256258
257259
:rtype: :class:`datetime.time`
258260
:returns: A datetime time object created from the string
259-
261+
:raises ValueError: if the value does not match a known format.
260262
"""
261-
return datetime.datetime.strptime(value, '%H:%M:%S').time()
263+
if len(value) == 8: # HH:MM:SS
264+
fmt = _TIMEONLY_NO_FRACTION
265+
elif len(value) == 15: # HH:MM:SS.micros
266+
fmt = _TIMEONLY_W_MICROS
267+
else:
268+
raise ValueError("Unknown time format: {}".format(value))
269+
return datetime.datetime.strptime(value, fmt).time()
262270

263271

264272
def _rfc3339_to_datetime(dt_str):

core/tests/unit/test__helpers.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,16 @@ def test_todays_date(self):
298298
WHEN = datetime.time(12, 9, 42)
299299
self.assertEqual(self._call_fut(("12:09:42")), WHEN)
300300

301+
def test_w_microseconds(self):
302+
import datetime
303+
304+
WHEN = datetime.time(12, 9, 42, 123456)
305+
self.assertEqual(self._call_fut(("12:09:42.123456")), WHEN)
306+
307+
def test_w_millis_fail(self):
308+
with self.assertRaises(ValueError):
309+
self._call_fut("12:09:42.123")
310+
301311

302312
class Test__rfc3339_to_datetime(unittest.TestCase):
303313

0 commit comments

Comments
 (0)