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

JavaScript

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

gives you

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