如何在python中比较ISO-8601日期

时间:2018-06-12 08:27:56

标签: python datetime iso8601

我有ISO-8601格式的日期

date="2018-03-13T17:22:20.065Z"

我希望以UTC格式找到当前iso9621时间。 我找到了一些代码段,例如datetime.datetime.utcnow().isoformat()

给出了以下结果

2018-06-12T08:19:28.954375

我想知道提供的日期是否超过30天。

我试图解决它,如下所示 question

import datetime
import dateutil.parser

insertion_date = dateutil.parser.parse('2018-03-13T17:22:20.065Z')
diffretiation=datetime.datetime.utcnow().isoformat() - insertion_date


print diffretiation 
print insertion_date

if diffretiation.days>30:
    print "The insertion date is older than 30 days"

else:
    print "The insertion date is not older than 30 days"

我在这里发现了以下错误

Traceback (most recent call last):
  File "test2.py", line 5, in <module>
    right_now_30_days_ago=datetime.datetime.utcnow().isoformat() - insertion_date
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'

任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

您的datetime.datetime.utcnow()时区未发现,要让其知道使用pytz

import datetime
import dateutil.parser
import pytz

insertion_date = dateutil.parser.parse('2018-03-13T17:22:20.065Z')
diffretiation = pytz.utc.localize(datetime.datetime.utcnow()) - insertion_date


print diffretiation 
print insertion_date

if diffretiation.days>30:
    print "The insertion date is older than 30 days"

else:
    print "The insertion date is not older than 30 days"
#The insertion date is older than 30 days

P.S。 datetime.datetime.utcnow().isoformat()返回一个字符串,这就是您遇到的错误。