是否可以将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
你几乎得到了它。
hour
,min
和seconds
是整数,整数没有hour
,minute
或second
属性。
更改
hello = datetime.time(hour.hour, min.minute, seconds.second)
至
hello = datetime.time(hour, min, seconds)
作为旁注,t = int(x)
是完全没必要的,因为x
已经是int
。
作为附注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