comparing datetime with date

Andrew Durdin adurdin at gmail.com
Thu Sep 16 20:43:52 EDT 2004


> Steve Holden <sholden at holdenweb.com> wrote:
> 
> > Well you do, of course, allow that this appeals to *your* intuition, but
> > it seems much more reasonable to me to assume that a date, when compared
> > to a datetime, should specify a single canonical time (such as midnight
> > at the start of that date).

My POV mostly comes from having to deal with comparing a date to an
inclusive range of dates (i.e. time is unimportant) where the dates
are stored (implicitly) as datetimes with a midnight time: 3/9/04 <= x
<= 17/9/04  (using dd/mm/yy)
In this case, the equality will fail if x happens to be 17/9/04
00:00:01 or later, and the solution of having to increment the day of
the right endpoint of the range is both inconvenient and non-obvious
(when reading the code). Of course, python's separate datetime, date,
and time types allow for a better solution to this problem: use the
date type only.

On Wed, 15 Sep 2004 16:13:28 +0200, Alex Martelli <aleaxit at yahoo.com> wrote:
> This means == does not define an equivalence relationship, and THAT is
> enough to send me into shivers and cold sweating.  Either having a
> comparison between date and datetime raise an exception, or consider a
> date to be == to ONE specific datetime, will be OK from this POV.  As
> for which choice is better, if I was the one tasked to design this, I'd
> go for "In the face of ambiguity, refuse the temptation to guess", and
> raise an exception.  But I don't feel particularly strongly about this.

It looks like there are some discrepancies between comparison handling
between the datetime types, though:
>>> import datetime
>>> d = datetime.date(2004,9,17)
>>> t = datetime.time(10,28,47)
>>> dt = datetime.datetime(2004,9,17,10,28,47)
>>> dt == d
True
>>> dt == t
False
>>> d == t
False
>>> dt < d
False
>>> dt < t
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't compare datetime.datetime to datetime.time
>>> d < t
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't compare datetime.date to datetime.time

You can compare a datetime and a time for equality, but not for
inequality. A datetime and date can be compared for both. It is
probably better to raise an exception for any comparison between time
and datetime, time and date, or date and datetime. If the former or
latter are desired, then the date() and time() methods of the datetime
object can be used to explicitly get a comparable object.



More information about the Python-list mailing list