pythoniso8601timedeltapython-datetime

Convert a datetime.timedelta into ISO 8601 duration in Python?


Given a datetime.timedelta, how to convert it into an ISO 8601 duration string?

For example, given datetime.timedelta(0, 18, 179651), how do I get 'PT18.179651S'?


For the reverse, see Is there an easy way to convert ISO 8601 duration to timedelta?.


Solution

  • Although the datetime module contains an implementation for a ISO 8601 notation for datetime or date objects, it does not currently (Python 3.7) support the same for timedelta objects. However, the isodate module (pypi link) has functionality to generate a duration string in ISO 8601 notation:

    In [15]: import isodate, datetime
    
    In [16]: print(isodate.duration_isoformat(datetime.datetime.now() - datetime.datetime(1985, 8, 13, 15)))
    P12148DT4H20M39.47017S
    

    which means 12148 days, 4 hours, 20 minutes, 39.47017 seconds.