Skip to content
Advertisement

Python using Regular Expression to convert a string

I want to convert the duration variable from YouTube Data api?

PT1M6S –> 1:06
PT38S –> 0:38
PT58M4 –> 58:04

Here is my codes:

p[‘duration’] is the value from json data

duration = re.sub(r'^PT',r'',p['duration'])
duration = re.sub(r'M',r':',duration)
if (len(p['duration']) > 5 ):
    duration = re.sub(r'S',r'',duration)
else:
    duration = "0:" + re.sub(r'S',r'',duration)

Is there a simple way to do in one regex statement?

Thanks!

Advertisement

Answer

An alternative to using a regex is using parser from dateutil. It has an option fuzzy that you can use to convert your data to datetime. If you subtract midnight today from that, you get the value as a timedelta:

from dateutil import parser
from datetime import date
from datetime import datetime

lst = ['PT1M6S','PT38S', 'PT58M4']

for t in lst:
    print(parser.parse(t, fuzzy=True) - datetime.combine(date.today(), datetime.min.time()))

gives you

0:01:06
0:00:38
0:58:04

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement