根据标题,我正在尝试解析一个包含以下内容的 XML 文件:xs:duration http://www.w3schools.com/Schema/schema_dtypes_date.asp#duration数据类型。我想把它转换成Pythontimedelta http://docs.python.org/library/datetime.html#timedelta-objects对象,然后我可以在进一步的计算中使用它。
是否有任何内置的方法可以做到这一点,类似于strptime() http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior功能?如果没有,实现这一目标的最佳方法是什么?
鉴于我已经有一个关于我在问题中提出的问题的工作示例,为了完整起见,我将其发布在这里。如果有更好的答案出现,我会接受。
period = '-P14D'
regex = re.compile('(?P<sign>-?)P(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?')
# Fetch the match groups with default value of 0 (not None)
duration = regex.match(period).groupdict(0)
# Create the timedelta object from extracted groups
delta = timedelta(days=int(duration['days']) + (int(duration['months']) * 30) + (int(duration['years']) * 365),
hours=int(duration['hours']),
minutes=int(duration['minutes']),
seconds=int(duration['seconds']))
if duration['sign'] == "-":
delta *= -1
这可行,但无法正确处理月份长度或闰年。就我而言,这不是问题,但值得记住。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)