有没有一种简单的方法可以将 ISO 8601 持续时间转换为 timedelta?

2024-04-01

我怎样才能转换ISO 8601 持续时间字符串 https://en.wikipedia.org/wiki/ISO_8601#Durations to datetime.timedelta https://docs.python.org/3/library/datetime.html#datetime.timedelta?

我尝试只是实例化timedelta带有持续时间字符串和格式字符串,但我得到一个例外:

>>> from datetime import timedelta
>>> timedelta("PT1H5M26S", "T%H%M%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported type for timedelta seconds component: str

For the reverse, see Convert a datetime.timedelta into ISO 8601 duration in Python? https://stackoverflow.com/questions/27168175.


I found isodate https://pypi.python.org/pypi/isodate图书馆做我想做的事

isodate.parse_duration('PT1H5M26S')
  • 您可以阅读该函数的源代码here https://github.com/gweis/isodate/blob/27cebc56a0f6a900eeb897512879d545095f410b/src/isodate/isoduration.py#L57-L130
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有一种简单的方法可以将 ISO 8601 持续时间转换为 timedelta? 的相关文章

随机推荐