Reputation: 35374
I'm comparing two time
objects with different timezones, and looks like it's actually ignoring the timezone, testing only the hour/minute/second components.
Let's create two time
objects:
from datetime import time
import pytz
CET = pytz.timezone('CET')
Japan = pytz.timezone('Japan')
t1 = time(1,2,3, tzinfo=CET)
t2 = time(1,2,3, tzinfo=Japan)
Printing them, we see that they're pretty different:
datetime.time(1, 2, 3, tzinfo=<DstTzInfo 'CET' CET+1:00:00 STD>)
datetime.time(1, 2, 3, tzinfo=<DstTzInfo 'Japan' JST+9:00:00 STD>)
Now, let's compare them:
t1 == t2
#-> True
Ehm, what? How is it possible that Python treats them equal?
Upvotes: 7
Views: 2210
Reputation: 2310
I would use (t1,t1.tzinfo) == (t2, t2.tzinfo)
or t1.strftime('%H %M %S %Z') == t2.strftime('%H %M %S %Z')
this to check equality.
derp explained why Python treated t1 and t2 equal and also refer this supported operations (Python docs).
More references:
According to pytz docs,
The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.
pytz docs shows the way to convert (using localize and/or replace) naive time objects
to aware time objects
and also present ways to perform arithmetic over time objects.
Upvotes: 0
Reputation: 26375
Both of your time objects are "naive" according to https://docs.python.org/2/library/datetime.html#datetime.tzinfo:
A
time
object t is aware ift.tzinfo
is notNone
andt.tzinfo.utcoffset(None)
does not returnNone
. Otherwise, t is naive.
print(t1.tzinfo, t1.tzinfo.utcoffset(None))
print(t2.tzinfo, t2.tzinfo.utcoffset(None))
Gives us:
(<DstTzInfo 'CET' CET+1:00:00 STD>, None)
(<DstTzInfo 'Japan' JST+9:00:00 STD>, None)
https://docs.python.org/2/library/datetime.html#module-datetime
A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects.
In other words: the objects have no date and so it cannot be determined whether or not daylight saving time applies. They're ambiguous, and running t.utcoffset()
for either will return None
. Which leaves the timezones being ignored entirely in the comparison because they're effectively meaningless.
Upvotes: 8
Reputation: 122376
From the docs regarding naive and aware time objects:
A time object t is aware if t.tzinfo is not None and t.tzinfo.utcoffset(None) does not return None.
In your case, both t1
and t2
return None
for t1.tzinfo.utcoffset(None)
and t2.tzinfo.utcoffset(None)
. Hence your objects are naive and not aware.
So effectively you're comparing '01:02:03' with '01:02:03' which is True
.
Upvotes: 2