Soviero
Soviero

Reputation: 1902

Odd output from modulo division in Python

Given the following example:

seconds = totalTime % 60
minutes = (totalTime - seconds) % (60 ** 2)
hours = (totalTime - (minutes * 60)) / (60 ** 2)

finalTime = '{0:.0f}h {1:.0f}m {2:.0f}s'.format(hours, minutes, seconds)

When I set totalTime to 7000 for example (a little under two hours), I get the following in return:

-55h 3360m 39s

Huh!? This happens with any number numbers i give it... Heres one more example if it help:

totalTime = 10000

-44h 2760m 39s

Upvotes: 1

Views: 271

Answers (3)

Albert Veli
Albert Veli

Reputation: 2109

Hmm, I think the correct expressions would be:

seconds = totalTime % 60
minutes = (totalTime / 60) % 60
hours = totalTime / (60 ** 2)

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308500

Your minutes is actually measured in seconds. Do a divide by 60 in there somewhere.

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 602475

You are measuring the minutes in seconds. To fix your code, you should divide minutes by 60:

minutes = (totalTime - seconds) % (60 ** 2) / 60

However, there are much easier ways to do this, for example

hours, seconds = divmod(totalTime, 60 ** 2)
minutes, seconds = divmod(seconds, 60)

Upvotes: 8

Related Questions