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 = '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 'P' + date + time
Convert a datetime.timedelta into ISO 8601 duration in Python?