Python compares datetimes with different time zones

I am implementing a function with a scheduled publication of an object. The user chooses the time to publish, and I created a cron task to run every minute and check if there is a publication time.

Users from different time zones.

So, I need to compare two datetime times:

>>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 the rather stupid question, but I need to discuss this. Thanks

+7
source share
2 answers

http://pytz.sourceforge.net/ is where you want to look, when you want to eliminate time zone differences :)

edit: just found this post in SO format which can give you more information about your problem

+3
source

Because the error says that you "cannot compare biased naive and biased dates and times." This means that you must compare two dates and times that both take into account the time zone or both are time zones (do not include the time zone). In your codes, curdate does not have time zone information and therefore cannot be compared with user_chosen_time, which takes into account the time zone.

You must first assign the correct time zone for each date and time. And then you can directly compare the two times with different time zones.

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, can you refer to Converting Python UTC Date and Time to Local Time Using Only the Standard Python Library? ,

0
source

All Articles