"PT" Formatted time string in python

Viewed 2158

I'm receiving a string which is formatted in the following way: "PTXMYS" Where X is the amount of minutes and Y is the amount of seconds.

I'd like to turn that string into an int which presents the amount of seconds in total. I tried using datetime and other stuff and it just won't work for me, I read online that this formatting is standard for iso8601 so it's weird for me that it doesn't really work.

String example:

x="PT4M13S"
2 Answers

there is a third-party library that can parse these strings, isodate:

import isodate
isodate.parse_duration("PT4M13S")
# datetime.timedelta(seconds=253)
isodate.parse_duration("PT4M13S").total_seconds()
# 253.0

And for completeness, there is an option to do this with datetime's strptime and timedelta's total_seconds():

from datetime import datetime, timedelta
# parse minute and second to datetime object:
t = datetime.strptime("PT4M13S","PT%MM%SS")
# convert to timedelta to get the total seconds
td = timedelta(minutes=t.minute, seconds=t.second)
td.total_seconds()
# 253

What you are trying to do can easily be solved using regex. Try this out:

import re
m, s = re.findall('PT(\d+)M(\d+)S',x)[0]
total_secs = 60*int(m) + int(s)
print(total_secs)

Output:

253
Related