Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle parsing ISO datetimes where the microseconds round up to 1s or more #1084

Merged
merged 3 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion ops/_private/timeconv.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def parse_rfc3339(s: str) -> datetime.datetime:
that Go's encoding/json package produces for time.Time values.

Unfortunately we can't use datetime.fromisoformat(), as that does not
support more than 6 digits for the fractional second, nor the 'Z' for UTC.
support more than 6 digits for the fractional second, nor the 'Z' for UTC,
in Python 3.8 (Python 3.11+ has the required functionality).
"""
match = _TIMESTAMP_RE.match(s)
if not match:
Expand All @@ -50,6 +51,9 @@ def parse_rfc3339(s: str) -> datetime.datetime:
tz = datetime.timezone(tz_delta if sign == '+' else -tz_delta)

microsecond = round(float(sfrac or '0') * 1000000)
# Ignore any overflow into the seconds - this aligns with the Python
# standard library behaviour.
microsecond = min(microsecond, 999999)

return datetime.datetime(int(y), int(m), int(d), int(hh), int(mm), int(ss),
microsecond=microsecond, tzinfo=tz)
6 changes: 6 additions & 0 deletions test/test_private.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ def test_parse_rfc3339(self):
self.assertEqual(timeconv.parse_rfc3339('2020-12-25T13:45:50.123456789+00:00'),
datetime.datetime(2020, 12, 25, 13, 45, 50, 123457, tzinfo=utc))

self.assertEqual(timeconv.parse_rfc3339('2006-08-28T13:20:00.9999999Z'),
datetime.datetime(2006, 8, 28, 13, 20, 0, 999999, tzinfo=utc))

self.assertEqual(timeconv.parse_rfc3339('2006-12-31T23:59:59.9999999Z'),
datetime.datetime(2006, 12, 31, 23, 59, 59, 999999, tzinfo=utc))

tzinfo = datetime.timezone(datetime.timedelta(hours=-11, minutes=-30))
self.assertEqual(timeconv.parse_rfc3339('2020-12-25T13:45:50.123456789-11:30'),
datetime.datetime(2020, 12, 25, 13, 45, 50, 123457, tzinfo=tzinfo))
Expand Down
Loading