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

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

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

``````# 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
``````