Comparing offset-aware and offset-naive datetimes?

Ben Finney ben+python at benfinney.id.au
Sun Jan 27 00:12:36 EST 2013


Roy Smith <roy at panix.com> writes:

> I have two datetimes.  One is offset-naive.  The other is offset-aware, 
> but I happen to know its offset is 0 (i.e. GMT).

Do you know the timezone of the offset-naive value?

Or is the above mixed up, and you mean “one is offset-aware; the other
is offset-naive, but I happen to know its offset is UTC+0”?

> How can I compare these?

Assuming you have a datetime value which is timezone-naive, and you have
no way of getting its timezone, and are unwilling to guess, you can't
sensibly compare that value to a datetime in a specific timezone::

    >>> import datetime
    >>> import pytz
    >>> timestamp_a = datetime.datetime(2012, 7, 1, 3, 45, 0)
    >>> timestamp_b = datetime.datetime(
    ...         2012, 8, 1, 20, 15, 0, tzinfo=pytz.UTC)
    >>> timestamp_a.tzinfo is None
    True
    >>> timestamp_b.tzinfo
    <UTC>
    >>> timestamp_a == timestamp_b
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can't compare offset-naive and offset-aware datetimes


So I'll assume that my interpretation about the mix-up is true, and that
you actually have a situation like the following::

    >>> import datetime
    >>> import pytz
    >>> timestamp_a = datetime.datetime(2012, 7, 1, 3, 45, 0)
    >>> timezone_for_a = pytz.UTC
    >>> timestamp_b = datetime.datetime(
    ...         2012, 8, 1, 20, 15, 0, tzinfo=pytz.timezone("Asia/Gaza"))
    >>> timestamp_a.tzinfo is None
    True
    >>> timestamp_b.tzinfo
    <DstTzInfo 'Asia/Gaza' EET+2:00:00 STD>

In which case, you can create a new timezone-aware value using the
timezone-naive value and the timezone you've decided to apply::

    >>> timestamp_c = timestamp_a.replace(tzinfo=timezone_for_a)
    >>> timestamp_c.tzinfo
    <UTC>
    >>> timestamp_c == timestamp_b
    False
    >>> timestamp_c > timestamp_b
    False
    >>> timestamp_c < timestamp_b
    True

> May the flies of a thousand Norwegian Blue parrots infest the armpits of 
> whoever invented timezones.

Heh. I'm fine with timezones; they are a good-enough solution to allow
our puny brains to speak about points in time in a reality that refuses
to accommodate our prejudice that the time of day is the same everywhere
on the globe.

What I'm not fine with is politicians who think it's a fun game to
fiddle with the specific timezone definitions with little advance notice
and leave we programmers to clean up the mess they keep making. Those
people are sorely in need of a nasal infestation of parrot fleas.

-- 
 \     “For every complex problem, there is a solution that is simple, |
  `\                               neat, and wrong.” —Henry L. Mencken |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list