1

I have a script which outputs the time taken by a command as follows:

real    112m5.559s
user    0m0.002s
sys     0m0.000s

I am parsing the output from the script using python. I want to represent the real time in seconds format. I have the parsed output in a variable real_time.

Here's how I am currently converting it to seconds format.

def gettime(x):
    m,s = map(float,x[:-1].split('m'))
    return 60 * m + s

real_time = "112m5.559s"
gettime(real_time)

Is there any other way to do this? (Probably a one liner which is more efficient)


timeit tests for the answers given below :

import pandas as pd

def gettime(x):
    m,s = map(float,x[:-1].split('m'))
    return 60 * m + s

real_time = "112m5.559s"

%timeit gettime(real_time)
%timeit int(real_time.split("m")[0]) * 60 + float(real_time.split("m")[1][:-1])
%timeit pd.to_timedelta(real_time).total_seconds()
%timeit sum(float(x) * 60 ** i for i, x in enumerate(reversed(real_time[:-1].split('m'))))

Output

1.27 µs ± 55.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.39 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
15.8 µs ± 714 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
2.63 µs ± 446 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Current method seems to be the efficient one. @bigbounty's answer comes close to being both efficient and one-liner.

Saurabh P Bhandari
  • 6,014
  • 1
  • 19
  • 50

3 Answers3

1
In [86]: int(real_time.split("m")[0]) * 60 + float(real_time.split("m")[1][:-1])
Out[86]: 6725.559
bigbounty
  • 16,526
  • 5
  • 37
  • 65
1

you can use pandas.to_timedelta() to directly parse the string, e.g.

pd.to_timedelta('112m5.559s').total_seconds()
Out[26]: 6725.559

However, your string splitting method seems more than 10x faster:

%timeit gettime('112m5.559s')
1.04 µs ± 18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit pd.to_timedelta('112m5.559s').total_seconds()
11.8 µs ± 214 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

...so I would stick with that.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

Refer to this answer for a similar question:- https://stackoverflow.com/a/6402934/10535841

As for the solution, using the technique used above,

real_time = '112m5.559s'
secs = sum(float(x) * 60 ** i for i, x in enumerate(reversed(real_time[:-1].split('m'))))
print(secs)