How to convert YouTube API duration to seconds?

前端 未结 7 1672
星月不相逢
星月不相逢 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条回答
  •  萌比男神i
    2021-02-07 05:47

    So this is what I came up with - a custom parser to interpret the time:

    def durationToSeconds(duration):
        """
        duration - ISO 8601 time format
        examples :
            'P1W2DT6H21M32S' - 1 week, 2 days, 6 hours, 21 mins, 32 secs,
            'PT7M15S' - 7 mins, 15 secs
        """
        split   = duration.split('T')
        period  = split[0]
        time    = split[1]
        timeD   = {}
    
        # days & weeks
        if len(period) > 1:
            timeD['days']  = int(period[-2:-1])
        if len(period) > 3:
            timeD['weeks'] = int(period[:-3].replace('P', ''))
    
        # hours, minutes & seconds
        if len(time.split('H')) > 1:
            timeD['hours'] = int(time.split('H')[0])
            time = time.split('H')[1]
        if len(time.split('M')) > 1:
            timeD['minutes'] = int(time.split('M')[0])
            time = time.split('M')[1]    
        if len(time.split('S')) > 1:
            timeD['seconds'] = int(time.split('S')[0])
    
        # convert to seconds
        timeS = timeD.get('weeks', 0)   * (7*24*60*60) + \
                timeD.get('days', 0)    * (24*60*60) + \
                timeD.get('hours', 0)   * (60*60) + \
                timeD.get('minutes', 0) * (60) + \
                timeD.get('seconds', 0)
    
        return timeS
    

    Now it probably is super non-cool and so on, but it works, so I'm sharing because I care about you people.

提交回复
热议问题