如何将 YouTube API 持续时间转换为秒? [英] How to convert YouTube API duration to seconds?
问题描述
为了感兴趣,我想将视频时长从 YouTube ISO 8601
转换为秒.为了将来证明我的解决方案,我选择了一段很长的视频来对其进行测试.>
API 在其持续时间内提供此 - "duration": "P1W2DT6H21M32S"
我尝试按照 stackoverflow.com/questions/969285.
import dateutil.parser持续时间 == dateutil.parser.parse('P1W2DT6H21M32S')
抛出异常
TypeError: 不支持 += 的操作数类型:'NoneType' 和 'int'
我错过了什么?
Python 的内置 dateutil 模块仅支持解析 ISO 8601 日期,不支持解析 ISO 8601 持续时间.为此,您可以使用isodate"库(在 pypi 中 https://pypi.python.org/pypi/isodate --通过 pip 或 easy_install 安装).该库完全支持 ISO 8601 持续时间,将它们转换为 datetime.timedelta 对象.因此,一旦您导入了库,就很简单:
导入isodatedur = isodate.parse_duration('P1W2DT6H21M32S')打印(dur.total_seconds())
For the sake of interest I want to convert video durations from YouTubes ISO 8601
to seconds. To future proof my solution, I picked a really long video to test it against.
The API provides this for its duration - "duration": "P1W2DT6H21M32S"
I tried parsing this duration with dateutil
as suggested in stackoverflow.com/questions/969285.
import dateutil.parser
duration = = dateutil.parser.parse('P1W2DT6H21M32S')
This throws an exception
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'int'
What am I missing?
Python's built-in dateutil module only supports parsing ISO 8601 dates, not ISO 8601 durations. For that, you can use the "isodate" library (in pypi at https://pypi.python.org/pypi/isodate -- install through pip or easy_install). This library has full support for ISO 8601 durations, converting them to datetime.timedelta objects. So once you've imported the library, it's as simple as:
import isodate
dur = isodate.parse_duration('P1W2DT6H21M32S')
print(dur.total_seconds())
这篇关于如何将 YouTube API 持续时间转换为秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!