Parsing xs syntax: duration into Python datetime.timedelta object?

As per the title, I am trying to parse an XML file that contains xs:duration

a datatype, I would like to convert this to Python timedelta

, which I can then use in further calculations.

Is there a built-in way to do this similarly strptime()

? If not, what is the best way to achieve this?

+2


a source to share


2 answers


Seeing that I already have a working example of what I asked in the question, I'll post it here for completeness. If there are any better answers, I agree.

period = '-P14D'
regex  = re.compile('(?P<sign>-?)P(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?')

# Fetch the match groups with default value of 0 (not None)
duration = regex.match(period).groupdict(0)

# Create the timedelta object from extracted groups
delta = timedelta(days=int(duration['days']) + (int(duration['months']) * 30) + (int(duration['years']) * 365),
                  hours=int(duration['hours']),
                  minutes=int(duration['minutes']),
                  seconds=int(duration['seconds']))

if duration['sign'] == "-":
    delta *= -1

      



This works, but will not handle month lengths or leap years correctly. For my purposes, this is not a problem, but worth keeping in mind.

+3


a source


This is an old question, but for future reference: it can be used for this isodate.parse_duration()

. It returns a class that is compatible with timedelta

.



See https://pypi.python.org/pypi/isodate

+4


a source







All Articles