How to convert YouTube API duration to seconds?

前端 未结 7 1529
星月不相逢
星月不相逢 2021-02-07 04:52

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

7条回答
  •  长发绾君心
    2021-02-07 05:37

    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

提交回复
热议问题