我试图确定 unix 时间戳是否在 21:00 之后。但是,我遇到了类型错误。
这是我的代码:
from datetime import datetime, time
theTime=1497204737
the_date = (
datetime.fromtimestamp(
int(theTime)
).strftime('%H:%M:%S')
)
if the_date >= time(21,00):
print("we did it!")
我不断收到此错误:
TypeError: '<=' not supported between instances of 'str' and 'datetime.time'
如何解决这个问题?
最佳答案
问题是您将时间戳转换为日期时间
,但随后再次将其转换为字符串:
>>> the_date = datetime.fromtimestamp(int(theTime)).strftime('%H:%M:%S')
>>> type(the_date)
str
有几种方法可以使其发挥作用:
例如,您可以简单地将时间戳保留为日期时间
并比较小时
:
from datetime import datetime, time
theTime=1497204737
the_date = datetime.fromtimestamp(int(theTime))
if the_date.hour >= 21:
print("we did it!")
或将日期时间
转换为时间
并比较时间
:
if time(the_date.hour, the_date.minute) >= time(21, 0):
print("we did it!")
关于Python:如何查看 Unix 时间戳是在一天中的某个时间之前还是之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44487411/