0
votes

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?

3

3 Answers

3
votes

This will happen any time you compare an offset-naive (datetime.now() No Timezone info) to an offset-aware (UTC) time. Python has poor timezone support by default. Even if you used datetime.utcnow() to compare this technically just returns you the UTC time but still has a naive timezone.

My suggestion is to install the pytz package and do:

import pytz

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

For further reference see: https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow

1
votes

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()
0
votes

You can do like below

print(datetime.today().timestamp() < object.datetime.timestamp())

or

object.datetime.timestamp()) > datetime.today().timestamp()