Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: cant compare offset-naive and offset-aware datetimes

I get datetime object from email message and then I try to compare it with datetime.now().

And then I see this error:

datetime.now() > datetime.strptime('Fri, 31 Jan 2020 09:59:34 +0000 (UTC)', "%a, %d %b %Y %H:%M:%S %z (%Z)"

TypeError: can't compare offset-naive and offset-aware datetimes

How to solve it?

like image 817
Yaroslav Avatar asked Dec 10 '22 01:12

Yaroslav


1 Answers

In many cases, you don't want to have to convert any time zone information. To prevent this, just convert the datetime objects to floats on both sides of the comparator. Use the datetime.timestamp() function.

I also suggest you simplify your date parsing with dateutil.parser.parse(). It's easier to read.

In your example, you might compare your datas like this:

compare_date = 'Fri, 31 Jan 2020 09:59:34 +0000 (UTC)'
datetime.now().timestamp() > parse(compare_date).timestamp()
like image 150
macetw Avatar answered May 24 '23 09:05

macetw