Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 998
Ebin Davis Avatar asked Nov 11 '18 12:11

Ebin Davis


2 Answers

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")
like image 189
PilouPili Avatar answered Sep 20 '22 18:09

PilouPili


You can use dateutil package and just convert your date string date to `datetime object and then check the condition with :

from dateutil import parser
past = datetime.now() - timedelta(days=90)
new_date = parser.parse("2018-11-10 10:55:31+00:00")
if past > new_date :
    print("This is older than 90 days")

that it : )

like image 37
ddor254 Avatar answered Sep 16 '22 18:09

ddor254