Ebi*_*vis 13 python string datetime python-datetime
我是 python 日期和时间类型的新手。
我有一个日期值。
date = '2018-11-10 10:55:31+00:00'
Run Code Online (Sandbox Code Playgroud)
我需要检查此日期值是否早于 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")
Run Code Online (Sandbox Code Playgroud)
失败并出现以下错误:
TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
这可能是因为“过去”的日期格式和我传递的日期值不同。
我怎么能想出这个?
Pil*_*ili 12
您必须使用strptime将字符串转换为日期。
比较运算符仅适用于日期时间。
date = datetime.strptime('2018-11-10 10:55:31', '%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)
那你能做吗
if past > date :
print("This is older than 90 days")
Run Code Online (Sandbox Code Playgroud)