iso8601 - Convert a datetime.timedelta into ISO 8601 duration in Python? -
given datetime.timedelta, how convert string of iso 8601 duration format?
ex,
>>> iso8601(datetime.timedelta(0, 18, 179651)) 'pt18.179651s'
this function tin can python project (apache license 2.0) can conversion:
def iso8601(value): # split seconds larger units 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) ## build date date = '' if days: date = '%sd' % days ## build time time = u't' # hours bigger_exists = date or hours if bigger_exists: time += '{:02}h'.format(hours) # minutes bigger_exists = bigger_exists or minutes if bigger_exists: time += '{:02}m'.format(minutes) # seconds if seconds.is_integer(): seconds = '{:02}'.format(int(seconds)) else: # 9 chars long w/leading 0, 6 digits after decimal seconds = '%09.6f' % seconds # remove trailing zeros seconds = seconds.rstrip('0') time += '{}s'.format(seconds) return u'p' + date + time
e.g.
>>> iso8601(datetime.timedelta(0, 18, 179651)) 'pt18.179651s'
Comments
Post a Comment