TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'

Ebin Davis picture Ebin Davis · Nov 11, 2018 · Viewed 38.2k times · Source

I am new to python date and time types.

I have a date value.

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

I need to check this date value is older than 90 days.

I tried :

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")

failing with the following error :
TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'

This might be because the date format for 'past' and the date value which I passed is different.

How can I come up with this ?

Answer

PilouPili picture PilouPili · Nov 11, 2018

You have to use strptime to convert a string into a date.

The comparaison operator only applies between datetime.

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

then can you do

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