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

问题描述 投票:0回答:2

是否可以将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

python python-3.x
2个回答
1
投票

你几乎得到了它。

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

更改

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

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

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

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


1
投票

您还可以将所有除法和模运算外包给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
© www.soinside.com 2019 - 2024. All rights reserved.