comparing datetime with date

Tim Peters tim.peters at gmail.com
Tue Sep 14 17:16:58 EDT 2004


[Donnal Walter]
> I was very surprised to discover that
> 
> >>> import datetime
> >>> x = datetime.date(2004, 9, 14)
> >>> y = datetime.datetime(2004, 9, 14, 6, 43, 15)
> >>> print x == y
> True
> 
> How can these two objects be considered equal?

They should not be.  Please open a bug report.  The problem is due to that 
datetime.datetime is a subclass of datetime.date:

>>> isinstance(y, datetime.date)
True
>>>

and date's comparison implementation believes that instances of date 
subclasses can be compared as if they *were* dates.  Indeed, since a datetime.
datetime is-a datetime.date, it's a bit hard to see why that shouldn't be 
allowed, and offhand I don't know of a principled way to fix this without 
breaking existing code that compares instances of user-defined subclasses of 
datetime.date to instances of datetime.date.



More information about the Python-list mailing list