2

I need to do this with just the math operators, but i always get ridiculously high numbers in the fields.

def main():
seconds = int(input('Seconds to be converted? '))
days = seconds / 86400
seconds = seconds - (days * 86400)
hours = seconds / 3600
seconds = seconds - (hours * 3600)
minutes = seconds / 60
seconds = seconds - (minutes * 60)

print('-------------')
print('You entered: ', seconds)
print('')
print('The converted time is: ', format(days, '1.0f'), ':', format(hours, '1.0f'), ':', format(minutes, '1.0f'), ':', format(seconds, '1.0f'))
WillShriver
  • 51
  • 1
  • 1
  • 4

4 Answers4

8

For maximum reusability, the datetime library would be handy for this:

For example, this code:

import datetime
s=12345
x=datetime.timedelta(seconds=s)
print x

Outputs:

3:25:45
  • 2
    **Thanks a lot. I just benchmarked this and it turns out that it is a very fast library, and it is included in Python! Great!** `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); elapsed = int(now-start_time); foo=datetime.timedelta(seconds=elapsed)"` result: `500000 loops, best of 5: 595 nsec per loop` (that's nanoseconds per call... and just for fun, ALL of the 500 THOUSAND runs of this test, which includes `time.time()` and `int()` truncation, the total runtime was just 297.5 milliseconds). So yeah don't worry about the performance! `datetime` is very fast. – Mitch McMabers Oct 14 '19 at 20:40
  • 4
    **FINAL UPDATE:** The benchmark was misleading. It creates the timedelta object very fast indeed. But if the user wants to have a STRING (H:MM:SS), they have to invoke the string conversion. One way to do that is to call `str()` on the datetime object. And that gives us the TRUE time for converting the time and making the string: `python -m timeit -s "import datetime; start_time = time.time() - 100" "now=time.time(); elapsed = int(now-start_time); foo=str(datetime.timedelta(seconds=elapsed))"` result is 1360 nanoseconds. So in fact it IS 16% slower than doing the math and formatting yourself. – Mitch McMabers Oct 14 '19 at 20:56
  • 3
    **FINAL UPDATE 2**: There's one more thing we should think about... The fact that most people who take the "manual algorithms" will place them in a utility function. I benchmarked that too: `python -m timeit -s "import datetime; start_time = time.time() -12345; convtime=lambda s: '{:01}:{:02}:{:02}'.format(s//3600, s%3600//60, s%60)" "now=time.time(); seconds = int(now-start_time); res = convtime(seconds)"` result is 1220 nanoseconds. Honestly it's so close to the timedelta library at that point that I'll just use `datetime.timedelta` instead. Thank you! I hope my comments help future humans! – Mitch McMabers Oct 14 '19 at 21:07
7
>>> s = 12345  # seconds
>>> '{:02}:{:02}:{:02}'.format(s//3600, s%3600//60, s%60)
'03:25:45'
JBernardo
  • 32,262
  • 10
  • 90
  • 115
  • Amazing, saves some overhead for the datetime/timedelta types when doing this large-scale. – Dirk Jan 25 '17 at 10:33
  • 1
    **Benchmark**. I just tested _this_ technique: `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); s = int(now-start_time); foo='{:01}:{:02}:{:02}'.format(s//3600, s%3600//60, s%60)"` result is 1180 nanoseconds. – Mitch McMabers Oct 14 '19 at 20:57
  • 1
    By the way, the math in this answer can be written as `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); s = int(now-start_time); hours, minutes, seconds = s//3600, s%3600//60, s%60"` which benchmarks identically to `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); seconds = int(now-start_time); hours, seconds = seconds // 3600, seconds % 3600; minutes, seconds = seconds // 60, seconds % 60"`, so there's no difference in this and the other manual answer. And I prefer your way of getting the hours, minutes and seconds variables. – Mitch McMabers Oct 14 '19 at 21:02
4

You should use integer division and modulus:

>>> seconds = 26264
>>> hours, seconds =  seconds // 3600, seconds % 3600
>>> minutes, seconds = seconds // 60, seconds % 60
>>> print hours, minutes, seconds
7 17 44
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
  • **Benchmark.** Your answer gets the hours, minutes and seconds pretty fast. But you'll wanna format it as a string for the user (H:MM:SS), and that makes it slower. Benchmark: `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); seconds = int(now-start_time); hours, seconds = seconds // 3600, seconds % 3600; minutes, seconds = seconds // 60, seconds % 60; foo='{:01}:{:02}:{:02}'.format(hours, minutes, seconds)"` result is 1180 nanoseconds. Compare that to the benchmark I posted on the `datetime.timedelta` answer. – Mitch McMabers Oct 14 '19 at 20:58
1

Maybe this:

>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'

Or this:

>>> import datetime
>>> datetime.timedelta(seconds=12345)
'03:25:45'
britodfbr
  • 1,747
  • 14
  • 16