Python:如何查看unix时间戳是在一天之前还是之后

时间:2017-06-11 18:41:01

标签: python python-3.x datetime

我正在试图弄清楚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'

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

问题是您将时间戳转换为datetime,但之后又将其转换为字符串:

>>> the_date = datetime.fromtimestamp(int(theTime)).strftime('%H:%M:%S')
>>> type(the_date)
str

有几种方法可以使它发挥作用:

例如,您只需将时间戳保持为datetime并比较hours

from datetime import datetime, time
theTime=1497204737

the_date = datetime.fromtimestamp(int(theTime))

if the_date.hour >= 21:
    print("we did it!")

或将datetime转换为time并比较time s:

if time(the_date.hour, the_date.minute) >= time(21, 0):
    print("we did it!")