MaSao93
MaSao93

Reputation: 202

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

Upvotes: 0

Views: 227

Answers (1)

MURTUZA BORIWALA
MURTUZA BORIWALA

Reputation: 555

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)

Upvotes: 1

Related Questions