Merge pull request #150 from goddenrich/fix-miliseconds-rfc3339-re

corrected regex to properly parse microseconds
This commit is contained in:
Kubernetes Prow Robot 2019-08-01 13:58:15 -07:00 committed by GitHub
commit ec31e05c90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 10 deletions

View File

@ -46,6 +46,8 @@ _re_rfc3339 = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)" # full-date
re.VERBOSE + re.IGNORECASE)
_re_timezone = re.compile(r"([-+])(\d\d?):?(\d\d)?")
MICROSEC_PER_SEC = 1000000
def parse_rfc3339(s):
if isinstance(s, datetime.datetime):
@ -57,8 +59,10 @@ def parse_rfc3339(s):
dt = [0] * 7
for x in range(6):
dt[x] = int(groups[x])
us = 0
if groups[6] is not None:
dt[6] = int(groups[6])
partial_sec = float(groups[6].replace(",", "."))
us = int(MICROSEC_PER_SEC * partial_sec)
tz = UTC
if groups[7] is not None and groups[7] != 'Z' and groups[7] != 'z':
tz_groups = _re_timezone.search(groups[7]).groups()
@ -72,7 +76,7 @@ def parse_rfc3339(s):
return datetime.datetime(
year=dt[0], month=dt[1], day=dt[2],
hour=dt[3], minute=dt[4], second=dt[5],
microsecond=dt[6], tzinfo=tz)
microsecond=us, tzinfo=tz)
def format_rfc3339(date_time):

View File

@ -22,24 +22,39 @@ from .dateutil import UTC, TimezoneInfo, format_rfc3339, parse_rfc3339
class DateUtilTest(unittest.TestCase):
def _parse_rfc3339_test(self, st, y, m, d, h, mn, s):
def _parse_rfc3339_test(self, st, y, m, d, h, mn, s, us):
actual = parse_rfc3339(st)
expected = datetime(y, m, d, h, mn, s, 0, UTC)
expected = datetime(y, m, d, h, mn, s, us, UTC)
self.assertEqual(expected, actual)
def test_parse_rfc3339(self):
self._parse_rfc3339_test("2017-07-25T04:44:21Z",
2017, 7, 25, 4, 44, 21)
2017, 7, 25, 4, 44, 21, 0)
self._parse_rfc3339_test("2017-07-25 04:44:21Z",
2017, 7, 25, 4, 44, 21)
2017, 7, 25, 4, 44, 21, 0)
self._parse_rfc3339_test("2017-07-25T04:44:21",
2017, 7, 25, 4, 44, 21)
2017, 7, 25, 4, 44, 21, 0)
self._parse_rfc3339_test("2017-07-25T04:44:21z",
2017, 7, 25, 4, 44, 21)
2017, 7, 25, 4, 44, 21, 0)
self._parse_rfc3339_test("2017-07-25T04:44:21+03:00",
2017, 7, 25, 1, 44, 21)
2017, 7, 25, 1, 44, 21, 0)
self._parse_rfc3339_test("2017-07-25T04:44:21-03:00",
2017, 7, 25, 7, 44, 21)
2017, 7, 25, 7, 44, 21, 0)
self._parse_rfc3339_test("2017-07-25T04:44:21,005Z",
2017, 7, 25, 4, 44, 21, 5000)
self._parse_rfc3339_test("2017-07-25T04:44:21.005Z",
2017, 7, 25, 4, 44, 21, 5000)
self._parse_rfc3339_test("2017-07-25 04:44:21.0050Z",
2017, 7, 25, 4, 44, 21, 5000)
self._parse_rfc3339_test("2017-07-25T04:44:21.5",
2017, 7, 25, 4, 44, 21, 500000)
self._parse_rfc3339_test("2017-07-25T04:44:21.005z",
2017, 7, 25, 4, 44, 21, 5000)
self._parse_rfc3339_test("2017-07-25T04:44:21.005+03:00",
2017, 7, 25, 1, 44, 21, 5000)
self._parse_rfc3339_test("2017-07-25T04:44:21.005-03:00",
2017, 7, 25, 7, 44, 21, 5000)
def test_format_rfc3339(self):
self.assertEqual(