python compare datetimes with different timezones

Feanor picture Feanor · Dec 4, 2012 · Viewed 10.9k times · Source

I'm implementing feature with scheduled publishing of object. User chooses the time to publish and i created a cron task to run every minute and check if it's the time to publish.

Users are from different timezones.

So i need to compare two datetimes:

>>user_chosen_time
datetime.datetime(2012, 12, 4, 14, 0, tzinfo=tzinfo(120))
>>curdate=datetime.datetime.now()
datetime.datetime(2012, 12, 4, 18, 4, 20, 17340)
>>user_chosen_time==curdate
*** TypeError: can't compare offset-naive and offset-aware datetimes

Sorry for rather stupid question but i need to discuss this. Thanks

Answer

Louis picture Louis · Dec 13, 2018

As the error suggests you "can't compare offset-naive and offset-aware datetimes". It means that you should compare two datetimes that are both timezone-aware or both timezone-naive (not timezone-aware). In your codes, curdate has no timezone info and thus could not be compared with user_chosen_time which is timezone-aware.

First you should assign correct timezone to each datetime. And then you could directly compare two datetimes with different timezones.

Example (with pytz):

import pytz
import datetime as dt

# create timezone
nytz=pytz.timezone('America/New_York')
jptz=pytz.timezone('Asia/Tokyo')

# randomly initiate two timestamps
a=dt.datetime(2018,12,13,11,2)
b=dt.datetime(2018,12,13,22,45)

# assign timezone to timestamps
a=nytz.localize(a)
b=jptz.localize(b)

# a = datetime.datetime(2018, 12, 13, 11, 2, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)
# b = datetime.datetime(2018, 12, 13, 22, 45, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)

a>b # True
b>a # False

For other methods you could refer to Convert a python UTC datetime to a local datetime using only python standard library?.