How to Parse ISO 8601 Durations in Python

A practical guide for developers

1. The Challenge of ISO 8601 Durations in Python

While Python's built-in datetime library is powerful for handling dates and times, it doesn't have a native way to parse ISO 8601 duration strings like P1Y2M3DT4H5M6S. This can be a challenge when you're working with APIs or data sources that use this standard format.

Fortunately, the third-party library isodate provides a simple and effective solution. This guide will walk you through how to use it.

2. Getting Started: Installing isodate

First, you need to install the library. You can do this easily using pip:

pip install isodate

3. Parsing a Duration String

The core function you'll use is isodate.parse_duration(). This function takes an ISO 8601 duration string as input and returns a datetime.timedelta object (for durations with weeks, days, hours, minutes, or seconds) or an isodate.duration.Duration object (for durations with years or months).

Here's a simple example:

import isodate
from datetime import timedelta

# A duration of 1 day, 2 hours, and 30 minutes
duration_string = "P1DT2H30M"

# Parse the duration
duration_obj = isodate.parse_duration(duration_string)

print(duration_obj)
# Output: 1 day, 2:30:00

# The object is a timedelta
print(type(duration_obj))
# Output: <class 'datetime.timedelta'>

4. Handling Years and Months

Because the length of years and months is not fixed, isodate handles them differently. When a duration string contains years or months, parse_duration returns a special isodate.duration.Duration object.

import isodate

# A duration of 1 year and 6 months
duration_string = "P1Y6M"

# Parse the duration
duration_obj = isodate.parse_duration(duration_string)

print(duration_obj)
# Output: P1Y6M

# The object is an isodate.duration.Duration
print(type(duration_obj))
# Output: <class 'isodate.duration.Duration'>

# You can access the components directly
print(f"Years: {duration_obj.years}, Months: {duration_obj.months}")
# Output: Years: 1, Months: 6

This object can then be added to a datetime.date or datetime.datetime object to perform date arithmetic correctly.

5. Next Steps and Resources

While isodate is the perfect tool for handling durations within a Python script, sometimes you need a quick way to validate a string or understand the format itself. For that, we have two great resources: