Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python compare datetimes with different timezones

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

like image 665
Feanor Avatar asked Dec 04 '12 16:12

Feanor


People also ask

Can you compare Datetimes in Python?

Use the datetime Module and the < / > Operator to Compare Two Dates in Python. datetime and simple comparison operators < or > can be used to compare two dates. The datetime module provides the timedelta method to manipulate dates and times.

How do I compare only time in Python?

Just call the . time() method of the datetime objects to get their hours, minutes, seconds and microseconds. Show activity on this post. Compare their times using datetime.

How do you get different time zones in Python?

Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.


2 Answers

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?.

like image 135
Louis Avatar answered Nov 14 '22 22:11

Louis


http://pytz.sourceforge.net/ is where you want to look when you want to eliminate the timezone differencies :)

edit: just found this post on SO that may give you a lot more informations on your problem

like image 26
Samuele Mattiuzzo Avatar answered Nov 14 '22 23:11

Samuele Mattiuzzo