反正将那些int转换成时间吗?

时间:2017-12-18 15:12:06

标签: python python-3.x

是否可以将int转换为小时:min:sec

import datetime 

x = 40000 

t = int(x) 

day = t//86400 
hour = (t-(day*86400))//3600 
min = (t - ((day*86400) + (hour*3600)))//60 
seconds = t - ((day*86400) + (hour*3600) + (min*60)) 

hello= datetime.time(hour.hour, min.minute, seconds.second)   

print (hello )

我想要这个输出: - 11:06:40

3 个答案:

答案 0 :(得分:2)

您还可以将所有除法和模运算外包给Python内置函数(请记住:batteries are included!)

>>> import time
>>> x = 40000 
>>> time.strftime('%H:%M:%S', time.gmtime(x))
'11:06:40'                    # <- that's your desired output
>>> time.gmtime(x)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=6, tm_sec=40, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(x).tm_hour    # <- that's how to access individual values
11

答案 1 :(得分:1)

你几乎得到了它。

hourminseconds是整数,整数没有hourminutesecond属性。

更改

hello = datetime.time(hour.hour, min.minute, seconds.second)

hello = datetime.time(hour, min, seconds)

作为旁注,t = int(x)完全没必要,因为x已经是int

作为附注2,将来请提供您收到的错误。

答案 2 :(得分:0)

注意:为了回应@Pavel 的回答,

您可能会发现 mainObj 没有给出您电脑上显示的正确时间。

要生成与您电脑上的时间一致的时间,请改用 time.gmtime(x)