Diogo Solipa
Diogo Solipa

Reputation: 13

Calculating time in MM:SS:TSHSTS

So I'm working with time to format seconds to the format MM:SS:TSHSTS, meaning minutes:seconds:1/10 second 1/100 second 1/1000 second. This is basicly to calculate lap times for a racing simulator.

My input comes in seconds so for instance 124.6073 seconds -> 02:04:607.

I've produced this function and it works, I just want to know how can I optimize this since in my head this is kinda hammered as I couldn't think of something better at the time.

def convert_lap_times(seconds_per_lap):

minutes = seconds_per_lap // 60
seconds = seconds_per_lap % 60
rest = seconds_per_lap % 1
rest_str = str(rest).split('0.')
decimal_rest = rest_str[1]

return "%02i:%02i.%0.3s" % (minutes, seconds, decimal_rest)

So the rest is the decimal part of said number and all worked fine until that point. The "big" issue becomes when I want to get rid of the integer part, for instance 0.607, I just wanted 607 so I parsed it as a string... is there a better way?

Thanks a lot and all the best!

Upvotes: 1

Views: 52

Answers (1)

Alain T.
Alain T.

Reputation: 42133

You could do it like this:

def convert_lap_times(seconds_per_lap):
    return "{:02.0f}:{:06.3f}".format(*divmod(seconds_per_lap,60))

print(convert_lap_times(124.6073))  # 02:04.607

Upvotes: 2

Related Questions