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
JavaScript
x
7
1
duration = re.sub(r'^PT',r'',p['duration'])
2
duration = re.sub(r'M',r':',duration)
3
if (len(p['duration']) > 5 ):
4
duration = re.sub(r'S',r'',duration)
5
else:
6
duration = "0:" + re.sub(r'S',r'',duration)
7
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
:
JavaScript
1
9
1
from dateutil import parser
2
from datetime import date
3
from datetime import datetime
4
5
lst = ['PT1M6S','PT38S', 'PT58M4']
6
7
for t in lst:
8
print(parser.parse(t, fuzzy=True) - datetime.combine(date.today(), datetime.min.time()))
9
gives you
JavaScript
1
5
1
0:01:06
2
0:00:38
3
0:58:04
4
5