Search code examples
pythonpython-re

Converting Youtube Data API V3 video duration format to seconds in Python3


I wanna convert the Youtube Data API V3 video duration format to seconds in python. ex:

PT1H
PT23M
PT45S
PT1H23M
PT1H45S
PT23M45S
PT1H23M45S

I think I need to use the re in python but I dont have enough experience in re. If you provide the code to convert the duration format to seconds, it will be appreciated to me. I am following this link


Solution

  • Here is the code to achive what you have asked:

    import datetime
    
    given_string = 'PT1H23M45S'
    new_string = given_string.split('T')[1]
    
    if 'H' in new_string and 'M' in new_string and 'S' in new_string:
        dt = datetime.datetime.strptime(new_string, '%HH%MM%SS')
        time_sec = int(dt.hour) * 3600 + int(dt.minute) * 60 + int(dt.second)
    
    elif 'M' in new_string and 'S' in new_string:
        dt = datetime.datetime.strptime(new_string, '%MM%SS')
        time_sec = int(dt.minute) * 60 + int(dt.second)
    
    elif 'H' in new_string and 'M' in new_string:
        dt = datetime.datetime.strptime(new_string, '%HH%MM')
        time_sec = int(dt.hour) * 3600 + int(dt.minute) * 60
    
    elif 'H' in new_string and 'S' in new_string:
        dt = datetime.datetime.strptime(new_string, '%HH%SS')
        time_sec = int(dt.hour) * 3600 + int(dt.second)
    
    elif 'H' in new_string:
        dt = datetime.datetime.strptime(new_string, '%HH')
        time_sec = int(dt.hour) * 3600
    
    elif 'M' in new_string:
        dt = datetime.datetime.strptime(new_string, '%HH')
        time_sec = int(dt.hour) * 60
    
    else:
        dt = datetime.datetime.strptime(new_string, '%SS')
        time_sec = int(dt.second)
    
    print(time_sec)