加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:37:16 所属栏目:Python 来源:网络整理
导读:我正在寻找一个 Python(v2)库,这将允许我解析和比较可能在不同单位的ISO 8601持续时间 理想情况下,它可以与标准运算符一起使用(a b)但是我会很喜欢a.compare(b)或者. 像这样的东西: duration('P23M') duration('P2Y') //Trueduration('P25M') duration('P2Y
我正在寻找一个 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读