Saurabh P Bhandari
Saurabh P Bhandari

Reputation: 6762

Convert time command output to seconds

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.

Upvotes: 1

Views: 738

Answers (3)

FObersteiner
FObersteiner

Reputation: 25664

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.

Upvotes: 1

Suryansu Dash
Suryansu Dash

Reputation: 95

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)

Upvotes: 0

bigbounty
bigbounty

Reputation: 17408

In [86]: int(real_time.split("m")[0]) * 60 + float(real_time.split("m")[1][:-1])
Out[86]: 6725.559

Upvotes: 1

Related Questions