WillShriver
WillShriver

Reputation: 61

How to convert seconds into hh:mm:ss in python 3.x

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'))

Upvotes: 3

Views: 14775

Answers (4)

britodfbr
britodfbr

Reputation: 2001

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'

Upvotes: 1

user764357
user764357

Reputation:

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

Upvotes: 10

Steinar Lima
Steinar Lima

Reputation: 7821

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

Upvotes: 4

JBernardo
JBernardo

Reputation: 33407

>>> s = 12345  # seconds
>>> '{:02}:{:02}:{:02}'.format(s//3600, s%3600//60, s%60)
'03:25:45'

Upvotes: 7

Related Questions