在Python中将datetime.timedelta转换为ISO 8601持续时间?

Dra*_*uan 7 python iso8601 timedelta python-datetime

给定datetime.timedelta,如何将其转换为ISO 8601持续时间格式的字符串?

当然,

>>> iso8601(datetime.timedelta(0, 18, 179651))
'PT18.179651S'
Run Code Online (Sandbox Code Playgroud)

ger*_*rit 7

尽管该datetime模块包含对datetimedate对象的 ISO 8601 表示法的实现,但它目前(Python 3.7)不支持timedelta对象的相同。但是,该isodate模块(pypi 链接)具有以 ISO 8601 表示法生成持续时间字符串的功能:

In [15]: import isodate, datetime

In [16]: print(isodate.duration_isoformat(datetime.datetime.now() - datetime.datetime(1985, 8, 13, 15)))
P12148DT4H20M39.47017S
Run Code Online (Sandbox Code Playgroud)

这意味着 12148 天 4 小时 20 分 39.47017 秒。


man*_*lio 5

这是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
Run Code Online (Sandbox Code Playgroud)

例如

>>> iso8601(datetime.timedelta(0, 18, 179651))
'PT18.179651S'
Run Code Online (Sandbox Code Playgroud)

  • 更好使用:isodate.duration_isoformat(timedelta) (2认同)