Ivan Yakushenko
Ivan Yakushenko

Reputation: 169

How to compare same time in different time zone?

I have 2 timestamps with different time zones:

date_1_str = '20200520090000' # GMT+2
date_2_str = '20 May 2020, 07:00' # UTC

I convert them to a datetime:

from datetime import datetime
from dateutil import tz

date_1 = datetime.strptime(date_1_str, '%Y%m%d%H%M%S').replace(tzinfo=tz.tzoffset('GMT+2', 0))
date_2 = datetime.strptime(date_2_str, '%d %b %Y, %H:%M').replace(tzinfo=tz.tzoffset('UTC', 0))

After that, I convert them to the local time zone to compare:

date_1_ = date_1.astimezone(tz.tzlocal())
# datetime.datetime(2020, 5, 20, 12, 0, tzinfo=tzlocal())

date_2_ = date_2.astimezone(tz.tzlocal())
# datetime.datetime(2020, 5, 20, 10, 0, tzinfo=tzlocal())

As you can see, it turned out not what I wanted, although in the case of UTC the conversion is correct. After conversion, both objects should be datetime.datetime(2020, 5, 20, 10, 0, tzinfo=tzlocal()) because my time zone is gmt+3 so 7.00 utc == 10.00 gmt+3 and 9.00 gmt+2 must be == 10.00 gmt+3 Where am I wrong?

Upvotes: 0

Views: 87

Answers (1)

FObersteiner
FObersteiner

Reputation: 25544

both tzoffsets are 0 in your code; if you set them accordingly, you should get the correct output:

from datetime import datetime
from dateutil import tz

date_1_str = '20200520090000' # GMT+2
date_2_str = '20 May 2020, 07:00' # UTC
date_1 = datetime.strptime(date_1_str, '%Y%m%d%H%M%S').replace(tzinfo=tz.tzoffset('GMT+2', 2*3600))
date_2 = datetime.strptime(date_2_str, '%d %b %Y, %H:%M').replace(tzinfo=tz.tzoffset('UTC', 0))

# I'm on UTC+2, so the hour should stay the same:
date_1_ = date_1.astimezone(tz.tzlocal())
# datetime.datetime(2020, 5, 20, 9, 0, tzinfo=tzlocal())

# UTC hour should be +2:
date_2_ = date_2.astimezone(tz.tzlocal())
# datetime.datetime(2020, 5, 20, 9, 0, tzinfo=tzlocal())

Upvotes: 1

Related Questions