Answer a question

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?

Answers

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())
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐