python - 类型错误 : '>' not supported between instances of 'datetime.datetime' and 'str'

标签 python string datetime python-datetime

我是 python 日期和时间类型的新手。

我有一个日期值。

date = '2018-11-10 10:55:31+00:00'

我需要检查此日期值是否早于 90 天。

我试过 :
from datetime import datetime
from datetime import timedelta

past = datetime.now() - timedelta(days=90)
date = '2018-11-10 10:55:31+00:00'

if past > date :
   print("This is older than 90 days")

失败并出现以下错误:TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
这可能是因为“过去”的日期格式和我传递的日期值不同。

我怎么能想出这个?

最佳答案

您必须使用 strptime将字符串转换为日期。

比较运算符仅适用于日期时间。

date = datetime.strptime('2018-11-10 10:55:31', '%Y-%m-%d %H:%M:%S')

那你能做吗
if past > date :
   print("This is older than 90 days")

关于python - 类型错误 : '>' not supported between instances of 'datetime.datetime' and 'str' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248537/

相关文章:

python - sqlalchemy.exc.ResourceClosedError : This transaction is closed 错误

javascript - 如何找到缺少字母的匹配字符串?

python正则表达式向前看正+负

python - 运行 GAE 开发服务器时,本地 MySQLdb 连接失败并出现 AttributeError for paramstyle

python - 删除 matplotlib 子图并避免留空

algorithm - 一个非常复杂的工作日/小时/分钟 sla 计算要弄清楚

MySQL 相同查询不同条件

java - 处理非常大的字符串 Java

c# - 如何使用字符串定界符拆分字符串?

java - 尝试将 PDT 中的日期时间解析为 ZonedDateTime 表示