John
John

Reputation: 2952

Why isn't my code working to make datetime objects timezone-aware?

I have two python datetime objects that represent the same moment in time:

a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)

Both are coming from different sources. I know that the first is in UTC, and the second is in "America/Edmonton" (MDT). Neither initially have a timezone attached to them.

I need to add timezones to these objects and compare them in a way where a == b is True.

What I did was this:

import datetime
from pytz import timezone

a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)

a = a.replace(tzinfo=timezone("UTC"))
b = b.replace(tzinfo=timezone("America/Edmonton"))

a = a.astimezone(timezone("America/Edmonton"))
b = b.astimezone(timezone("America/Edmonton"))

print(repr(a))
# Result: datetime.datetime(2018, 10, 28, 7, 26, 30, tzinfo=<DstTzInfo 'America/Edmonton' MDT-1 day, 18:00:00 DST>)

print(repr(b))
# Result: datetime.datetime(2018, 10, 28, 7, 26, 30, tzinfo=<DstTzInfo 'America/Edmonton' LMT-1 day, 16:26:00 STD>)

a == b # Results in False for some reason

What is "MDT-1 day, 18:00:00 DST" vs "LMT-1 day, 16:26:00 STD"? Why are they different? What am I doing wrong?

Upvotes: 3

Views: 162

Answers (1)

John
John

Reputation: 2952

The proper way to do this appears to be:

import datetime
from pytz import timezone

a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)

a = timezone('UTC').localize(a)
b = timezone('America/Edmonton').localize(b)

a == b

As demonstrated here. This does result in a being equal to b. Still not sure why it sounds like pytz is defaulting to using a system from before 1893.

Upvotes: 1

Related Questions