Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'))
like image 787
WillShriver Avatar asked Oct 24 '25 03:10

WillShriver


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!