Skip to content

Commit 3809303

Browse files
committed
Add support for microsecond on strptime
1 parent d184e7b commit 3809303

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Lib/_strptime.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def __init__(self, locale_time=None):
210210
#XXX: Does 'Y' need to worry about having less or more than
211211
# 4 digits?
212212
'Y': r"(?P<Y>\d\d\d\d)",
213-
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d)?|Z)",
213+
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|Z)",
214214
'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
215215
'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
216216
'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
@@ -467,7 +467,9 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
467467
hours = int(z[1:3])
468468
minutes = int(z[3:5])
469469
seconds = int(z[5:7] or 0)
470+
microseconds = int(z[8:] or 0)
470471
gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds
472+
gmtoff = gmtoff + (microseconds / (10**6))
471473
if z.startswith("-"):
472474
gmtoff = -gmtoff
473475
elif group_key == 'Z':

Lib/test/test_strptime.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,15 +327,31 @@ def test_offset(self):
327327
self.assertEqual(offset, -one_hour)
328328
(*_, offset), _ = _strptime._strptime("-013030", "%z")
329329
self.assertEqual(offset, -(one_hour + half_hour + half_minute))
330+
(*_, offset), _ = _strptime._strptime("-013030.000001", "%z")
331+
self.assertEqual(offset, -(one_hour + half_hour + half_minute + 0.000001))
330332
(*_, offset), _ = _strptime._strptime("+01:00", "%z")
331333
self.assertEqual(offset, one_hour)
332334
(*_, offset), _ = _strptime._strptime("-01:30", "%z")
333335
self.assertEqual(offset, -(one_hour + half_hour))
334336
(*_, offset), _ = _strptime._strptime("-01:30:30", "%z")
335337
self.assertEqual(offset, -(one_hour + half_hour + half_minute))
338+
(*_, offset), _ = _strptime._strptime("-01:30:30.000001", "%z")
339+
self.assertEqual(offset, -(one_hour + half_hour + half_minute + 0.000001))
336340
(*_, offset), _ = _strptime._strptime("Z", "%z")
337341
self.assertEqual(offset, 0)
338342

343+
def test_bad_offset(self):
344+
with self.assertRaises(ValueError):
345+
_strptime._strptime("-01:30:30.", "%z")
346+
with self.assertRaises(ValueError):
347+
_strptime._strptime("-0130:30", "%z")
348+
with self.assertRaises(ValueError):
349+
_strptime._strptime("-01:30:30.1234567", "%z")
350+
with self.assertRaises(ValueError):
351+
_strptime._strptime("-01:30:30:123456", "%z")
352+
with self.assertRaises(ValueError):
353+
_strptime._strptime("-01:3030", "%z")
354+
339355
def test_timezone(self):
340356
# Test timezone directives.
341357
# When gmtime() is used with %Z, entire result of strftime() is empty.

0 commit comments

Comments
 (0)