将 xs:duration 数据类型解析为 Python datetime.timedelta 对象?

发布于 2024-08-31 09:26:45 字数 589 浏览 11 评论 0原文

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

是否有任何内置方法可以执行此操作,类似于 strptime() 函数?如果没有,实现这一目标的最佳方法是什么?

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

马蹄踏│碎落叶 2024-09-07 09:26:45

鉴于我已经有一个关于我在问题中提出的问题的工作示例,为了完整起见,我将其发布在这里。如果有更好的答案出现,我会接受。

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

这可行,但无法正确处理月份长度或闰年。就我而言,这不是问题,但值得牢记。

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

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.

时光礼记 2024-09-07 09:26:45

这是一个老问题,但供将来参考:您可以为此使用 isodate.parse_duration() 。它返回一个与timedelta兼容的类。

请参阅 https://pypi.python.org/pypi/isodate

This is an old question, but for future reference: You can use isodate.parse_duration() for this. It returns a class that is compatible with timedelta.

See https://pypi.python.org/pypi/isodate

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文