Unclear datetime.date type when using isinstance

Diez B. Roggisch deets at web.de
Sat Oct 2 15:19:36 CEST 2010


"Mailing List" <lists at fastmail.net> writes:

> Was including a input check on a function argument which is expecting a
> datetime.date. When running unittest no exception was raised when a
> datetime.datetime instance was used as argument. Some playing with the
> console lead to this:
>
>>>> import datetime
>
>>>> dt1 = datetime.datetime(2010, 10, 2)
>>>> type(dt1)
> <type 'datetime.datetime'>
>>>> isinstance(dt1, datetime.datetime)
> True
>>>> isinstance(dt1, datetime.date)
> True
>
>>>> dt2 = datetime.date(2010, 10, 2)
>>>> type(dt2)
> <type 'datetime.date'>
>>>> isinstance(dt2, datetime.datetime)
> False
>>>> isinstance(dt2, datetime.date)
> True
>
> My issue (or misunderstanding) is in the first part, while dt1 is a
> datetime.date object (confirmed by type), the isinstance(dt1,
> datetime.datetime) returns True. Is this correct? If so, is it possible
> to verify whether an object is indeed a datetime.date and not a
> datetime.datetime object?

I think you got it wrong here: dt1 is a *datetime* object, and also a
date-object. I guess that's because it conforms to the same protocol -
it has year, month and day and so forth.

>
> For background information; reason my choice was to use the
> datetime.date object is that there should not be ay time information in
> the object. Of course this can easily be stripped off in the function,
> but thought the use of a datetime.date would be a nice shortcut...

Obviously not :) You can of course test not on inheritance (which
isinstance does), but actual type equality:

>>> type(dt1) == date
False


Diez




More information about the Python-list mailing list