有没有办法将这些 int 转换成时间?

新手上路,请多包涵

是否可以将 int 转换为 hours: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

原文由 Rajas Rasam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 771
2 个回答

您还可以将所有除法和模运算外包给 Python 内置函数(记住: 电池是包含在内的!)

 >>> 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

原文由 Pavel 发布,翻译遵循 CC BY-SA 3.0 许可协议

你几乎明白了。

hour , min and seconds are integers, and integers don’t have hour , minute or second 属性。

改变

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

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

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

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

原文由 DeepSpace 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题