Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"PT" Formatted time string in python

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"
like image 542
idan b Avatar asked Nov 15 '25 15:11

idan b


1 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
like image 162
FObersteiner Avatar answered Nov 17 '25 09:11

FObersteiner