我只需要数学运算符就可以做到这一点,但是我总是在字段中得到可笑的高数字。
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'))
答案 0 :(得分:4)
>>> s = 12345 # seconds
>>> '{:02}:{:02}:{:02}'.format(s//3600, s%3600//60, s%60)
'03:25:45'
答案 1 :(得分:4)
你应该使用整数除法和模数:
>>> seconds = 26264
>>> hours, seconds = seconds // 3600, seconds % 3600
>>> minutes, seconds = seconds // 60, seconds % 60
>>> print hours, minutes, seconds
7 17 44
答案 2 :(得分:4)
为了获得最大的可重用性,datetime
库对此非常方便:
例如,此代码:
import datetime
s=12345
x=datetime.timedelta(seconds=s)
print x
输出:
3:25:45
答案 3 :(得分:1)
也许是这样
>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'
或者这个:
>>> import datetime
>>> datetime.timedelta(seconds=12345)
'03:25:45'