This is a function from the Tin Can Python project (Apache License 2.0 version) that can perform the conversion:
def iso8601(value):
seconds = value.total_seconds()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
days, hours, minutes = map(int, (days, hours, minutes))
seconds = round(seconds, 6)
date = ''
if days:
date = '%sD' % days
time = u'T'
bigger_exists = date or hours
if bigger_exists:
time += '{:02}H'.format(hours)
bigger_exists = bigger_exists or minutes
if bigger_exists:
time += '{:02}M'.format(minutes)
if seconds.is_integer():
seconds = '{:02}'.format(int(seconds))
else:
seconds = '%09.6f' % seconds
seconds = seconds.rstrip('0')
time += '{}S'.format(seconds)
return u'P' + date + time
eg.
>>> iso8601(datetime.timedelta(0, 18, 179651))
'PT18.179651S'
source
share