给定datetime.timedelta,如何将其转换为ISO 8601持续时间格式的字符串?
例如,
>>> iso8601(datetime.timedelta(0, 18, 179651))
'PT18.179651S'
答案 0 :(得分:4)
这是Tin Can Python项目(Apache License 2.0)中可以进行转换的函数:
def iso8601(value):
# split seconds to 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'
答案 1 :(得分:0)
尽管datetime
module包含针对datetime
或date
对象的ISO 8601表示法的实现,但当前(Python 3.7)不支持timedelta
对象的实现。但是,isodate
module (pypi link)具有以ISO 8601表示法生成持续时间字符串的功能:
In [15]: import isodate, datetime
In [16]: print(isodate.duration_isoformat(datetime.datetime.now() - datetime.datetime(1985, 8, 13, 15)))
P12148DT4H20M39.47017S
这意味着12148天4小时20分钟39.47017秒。
答案 2 :(得分:0)
我试图编写一个较短的函数:
def iso8601(tdelta):
ts = tdelta.total_seconds()
d = int(ts // 86400)
s = round(ts % 60, 6)
hms = int(ts // 3600 % 24), int(ts // 60 % 60), s if s % 1 != 0 else int(s)
t = ''.join([str(p[0]) + p[1] for p in zip(hms, ['H', 'M', 'S']) if p[0]])
sep = 'T' if any(hms) else ''
return 'P' + (str(d) + 'D' if d else '') + sep + (t if ts else 'T0S')
例如
>>> iso8601(datetime.timedelta(0, 18, 179651))
'PT18.179651S'
对于某些人来说,这可能不太容易理解,但我认为在某些用例中将其拆开并内联起来会更容易。例如,如果您不使用timedelta,但持续时间以整数秒ts
为单位,并且例如,您的持续时间总是短于一天,则变为:
hms = ts // 3600, ts // 60 % 60, ts % 60
t = ''.join([str(p[0]) + p[1] for p in zip(hms, ['H', 'M', 'S']) if p[0]])
ts_iso8601 = 'PT' + t if ts else 'PT0S'
答案 3 :(得分:0)
请参阅 (ISO time (ISO 8601) in Python) ISO8601 可能包含时区偏移
import datetime
date=datetime.datetime.now().astimezone().isoformat()
2020-03-20T14:32:16.458361+13:00
date.isoformat()