Python:如何查看 Unix 时间戳是在一天中的某个时间之前还是之后

标签 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'

如何解决这个问题?

最佳答案

问题是您将时间戳转换为日期时间,但随后再次将其转换为字符串:

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

相关文章:

python - Pandas合并两个excel中的数据

python - 在本地调用 open_sftp() 和通过单独的函数调用有什么区别?

python - discord .py 的错误代码

python - 使用新数据库帮助 Django RemoteUserMiddleware RemoteUserBackend

python - 单独线程上的扭曲 react 器调用

python - 将 dict 转换为 defaultdict

python - 尝试使用 requests-html 抓取 JS Web 时出现问题(Python 3.6)

mysql - 在 MySql 中查找 n 天后是否有周年纪念日

Mysql:获取相应时间的最大值并按天分组

mysql - pad() 选择显示 2 个字符