Skip to content

Commit

Permalink
Merge 43b894e into 27cebc5
Browse files Browse the repository at this point in the history
  • Loading branch information
Flix6x committed Mar 4, 2021
2 parents 27cebc5 + 43b894e commit 59984e3
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions src/isodate/isoduration.py
Expand Up @@ -51,10 +51,10 @@
r"((?P<separator>T)(?P<hours>[0-9]+([,.][0-9]+)?H)?"
r"(?P<minutes>[0-9]+([,.][0-9]+)?M)?"
r"(?P<seconds>[0-9]+([,.][0-9]+)?S)?)?$")
# regular expression to parse ISO duartion strings.
# regular expression to parse ISO duration strings.


def parse_duration(datestring):
def parse_duration(datestring, as_timedelta_if_possible=True):
"""
Parses an ISO 8601 durations into datetime.timedelta or Duration objects.
Expand Down Expand Up @@ -89,17 +89,22 @@ def parse_duration(datestring):
# try alternative format:
if datestring.startswith("P"):
durdt = parse_datetime(datestring[1:])
if durdt.year != 0 or durdt.month != 0:
if (
as_timedelta_if_possible
and durdt.year == 0
and durdt.month == 0
):
# FIXME: currently not possible in alternative format
# create timedelta
ret = timedelta(days=durdt.day, seconds=durdt.second,
microseconds=durdt.microsecond,
minutes=durdt.minute, hours=durdt.hour)
else:
# create Duration
ret = Duration(days=durdt.day, seconds=durdt.second,
microseconds=durdt.microsecond,
minutes=durdt.minute, hours=durdt.hour,
months=durdt.month, years=durdt.year)
else: # FIXME: currently not possible in alternative format
# create timedelta
ret = timedelta(days=durdt.day, seconds=durdt.second,
microseconds=durdt.microsecond,
minutes=durdt.minute, hours=durdt.hour)
return ret
raise ISO8601Error("Unable to parse duration string %r" % datestring)
groups = match.groupdict()
Expand All @@ -114,7 +119,11 @@ def parse_duration(datestring):
# these values are passed into a timedelta object,
# which works with floats.
groups[key] = float(groups[key][:-1].replace(',', '.'))
if groups["years"] == 0 and groups["months"] == 0:
if (
as_timedelta_if_possible
and groups["years"] == 0
and groups["months"] == 0
):
ret = timedelta(days=groups["days"], hours=groups["hours"],
minutes=groups["minutes"], seconds=groups["seconds"],
weeks=groups["weeks"])
Expand Down

0 comments on commit 59984e3

Please sign in to comment.