Reputation: 6109
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 ?
Upvotes: 35
Views: 157429
Reputation: 164623
You need to convert your date string to datetime
. You can do this in a couple of ways.
datetime.strptime
For example, first convert to datetime
before your comparison. This requires you to specify the format precisely ahead of time:
date = '2018-11-10 10:55:31+00:00'
date = datetime.strptime(date[:-6], '%Y-%m-%d %H:%M:%S')
print(date)
datetime.datetime(2018, 11, 10, 10, 55, 31)
One popular tool is dateutil.parser
, which is able to parse most common datetime formats without the format specified in advance:
from datetime import datetime, timedelta
from dateutil import parser
past = datetime.now() - timedelta(days=90)
date1 = '2018-11-10 10:55:31+00:00'
date2 = '2017-11-10 10:55:31+00:00'
for date in (date1, date2):
if past > parser.parse(date[:-6]):
print(f'This is older than 90 days: {date}')
This is older than 90 days: 2017-11-10 10:55:31+00:00
Upvotes: 2
Reputation: 1628
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 : )
Upvotes: 5
Reputation: 2699
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")
Upvotes: 18