Skip to content

Commit

Permalink
add util.to_iso8601_duration()
Browse files Browse the repository at this point in the history
  • Loading branch information
snarfed committed Oct 24, 2019
1 parent 62367b8 commit 8152380
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
11 changes: 11 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,17 @@ def test_parse_iso8601_duration(self):
self.assertEqual(datetime.timedelta(*expected),
util.parse_iso8601_duration(input))

def test_to_iso8601_duration(self):
for bad in (None, 3, 4.5, '', 'bad'):
self.assertRaises(TypeError, util.to_iso8601_duration, bad)

for input, expected in (
((0, 0), 'P0DT0S'),
((1, 2), 'P1DT2S'),
((3, 4.5), 'P3DT4S'),
):
self.assertEqual(expected, util.to_iso8601_duration(datetime.timedelta(*input)))

def test_maybe_iso8601_to_rfc3339(self):
for input, expected in (
(None, None),
Expand Down
25 changes: 24 additions & 1 deletion util.py
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,8 @@ def parse_iso8601_duration(input):
https://en.wikipedia.org/wiki/ISO_8601#Durations
Returns:
timedelta, or None if input cannot be parsed as an ISO 8601 duration
:class:`datetime.timedelta`, or None if input cannot be parsed as an ISO
8601 duration
"""
if not input:
return None
Expand All @@ -765,6 +766,28 @@ def g(i):
hours=g(6), minutes=g(7), seconds=g(8))


def to_iso8601_duration(input):
"""Converts a timedelta to an ISO 8601 duration.
Returns a fairly strict format: 'PnMTnS'. Fractional seconds are silently
dropped.
Args:
input: :class:`datetime.timedelta`
https://en.wikipedia.org/wiki/ISO_8601#Durations
Returns:
string ISO 8601 duration, e.g. 'P3DT4S'
Raises: :class:`TypeError` if delta is not a :class:`datetime.timedelta`
"""
if not isinstance(input, datetime.timedelta):
raise TypeError('Expected datetime.timedelta, got %s' % input.__class__)

return 'P%sDT%sS' % (input.days, input.seconds)


def maybe_iso8601_to_rfc3339(input):
"""Tries to convert an ISO 8601 date/time string to RFC 3339.
Expand Down

0 comments on commit 8152380

Please sign in to comment.