How to compare ISO-8601 dates in python… here is a solution to the problem.
How to compare ISO-8601 dates in python
I have a date in ISO-8601 format
date="2018-03-13T17:22:20.065Z"
I want to find the current UTC
time in iso9621
format.
I found some code snippets like datetime.datetime.utcnow().isoformat().
This gives us the following results
2018-06-12T08:19:28.954375
I would like to know if the date provided is older than 30 days.
I tried to solve it as shown in the image
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"
I found the following error here
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'
It would be great to have any help here
Solution
Your datetime.datetime.utcnow()
is time zone unknown, use pytz
to let it know:
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()
returns a string, and that’s the error you’re experiencing.