编程语言
首页 > 编程语言> > 如何在Python中解析和比较ISO 8601持续时间?

如何在Python中解析和比较ISO 8601持续时间?

作者:互联网

我正在寻找一个Python(v2)库,这将允许我解析和比较可能在不同单位的ISO 8601持续时间

理想情况下,它可以与标准运算符一起使用(a< b)但是我会很喜欢a.compare(b)或者. 像这样的东西:

duration('P23M') < duration('P2Y') //True
duration('P25M') < duration('P2Y') //False

我已经安装了来自PyPi的isodate,但是它有自己的类,包括月份和年份,并且它们与自己或timedeltas都没有比较

解决方法:

这里有一点点持续时间(一个月是30天,一年是平均等):

# parse 8601 duration
from re import findall

def iso8601_duration_as_seconds( d ):
    if d[0] != 'P':
        raise ValueError('Not an ISO 8601 Duration string')
    seconds = 0
    # split by the 'T'
    for i, item in enumerate(d.split('T')):
        for number, unit in findall( '(?P<number>\d+)(?P<period>S|M|H|D|W|Y)', item ):
            # print '%s -> %s %s' % (d, number, unit )
            number = int(number)
            this = 0
            if unit == 'Y':
                this = number * 31557600 # 365.25
            elif unit == 'W': 
                this = number * 604800
            elif unit == 'D':
                this = number * 86400
            elif unit == 'H':
                this = number * 3600
            elif unit == 'M':
                # ambiguity ellivated with index i
                if i == 0:
                    this = number * 2678400 # assume 30 days
                    # print "MONTH!"
                else:
                    this = number * 60
            elif unit == 'S':
                this = number
            seconds = seconds + this
    return seconds

for d in [ 'PT10M', 'PT5H', 'P3D', 'PT45S', 'P8W', 'P7Y', 'PT5H10M', 'P2YT3H10M', 'P3Y6M4DT12H30M5S', 'P23M', 'P2Y' ]:
    seconds = iso8601_duration_as_seconds( d )
    print "%s \t= %s" % (d,seconds)
    print


print '%s' % (iso8601_duration_as_seconds('P23M') < iso8601_duration_as_seconds('P2Y') )
# True
print '%s' % (iso8601_duration_as_seconds('P25M') < iso8601_duration_as_seconds('P2Y') )
# False

标签:iso8601,python
来源: https://codeday.me/bug/20190728/1561582.html