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 a
Works on python 2.7+. Adopted from a JavaScript one-liner for Youtube v3 question here.
import re
def YTDurationToSeconds(duration):
match = re.match('PT(\d+H)?(\d+M)?(\d+S)?', duration).groups()
hours = _js_parseInt(match[0]) if match[0] else 0
minutes = _js_parseInt(match[1]) if match[1] else 0
seconds = _js_parseInt(match[2]) if match[2] else 0
return hours * 3600 + minutes * 60 + seconds
# js-like parseInt
# https://gist.github.com/douglasmiranda/2174255
def _js_parseInt(string):
return int(''.join([x for x in string if x.isdigit()]))
# example output
YTDurationToSeconds(u'PT15M33S')
# 933
Handles iso8061 duration format to extent Youtube Uses up to hours