将xs:duration数据类型解析为Python datetime.timedelta对象? [英] Parsing an xs:duration datatype into a Python datetime.timedelta object?

查看:196
本文介绍了将xs:duration数据类型解析为Python datetime.timedelta对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照标题,我正在尝试解析一个包含 xs:duration 数据类型。我想将其转换为Python timedelta 对象,然后我可以将其用于进一步的计算中。

As per the title, I'm trying to parse an XML file containing an xs:duration data type. I'd like to convert that into a Python timedelta object, which I can then use in further calculations.

是否有任何内置方式类似于 strptime() 函数?如果没有,那么实现此目标的最佳方法是什么?

Is there any built-in way of doing this, similar to the strptime() function? If not, what is the best way to achieve this?

推荐答案

我已经看到了我所要求的工作示例问题,出于完整性考虑,我将在此处发布。如果有更好的答案,我会接受。

Seeing as I already have a working example of what I asked in the question, I'll post it here for completeness. If any better answers come up I'll accept.

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

此方法有效,但不能正确处理月份长度或leap年。就我而言,这不是问题,但值得牢记。

This works, but won't handle the month lengths or leap years correctly. For my purposes this isn't an issue, but it is worth keeping in mind.

这篇关于将xs:duration数据类型解析为Python datetime.timedelta对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆