python datetime instance check with date returns true

Viewed 747

I have a 2 objects, one is datetime and the other is date object. When I want to check the type of object using isinstance(python's preferred way), I get a little absurd results

>>> from datetime import date, datetime
>>> a=date.today()
>>> b=datetime.now()
>>> isinstance(a, date)
True
>>> isinstance(a, datetime)
False
>>> isinstance(b, date)
True       # this should be False
>>> isinstance(b, datetime)
True

Why datetime object instance check with date returning true? Currently I am using type to overcome this issue, but isn't a workaround?

>>> type(a) == date
True
>>> type(a) == datetime
False
>>> type(b) == date
False
>>> type(b) == datetime
True
2 Answers

Why datetime object instance check with date returning true

there's no workaround, it works as intended, since datetime is a subclass of date and isinstance returns True for subclasses, as the docs say. I think using type() is the only way for you here.

>>> from datetime import datetime, date

>>> datetime.__mro__
(datetime.datetime, datetime.date, object)

>>> issubclass(datetime, date)
True

The datetime class is a subclass of date.

The Python library creates this inheritance relationship so that you can use a datetime where a date is wanted. The rationale for that is that a datetime object includes a date in it. If you ignore the time or use a fixed time (such as midnight) then it makes sense to use it as a date object.

The documentation mentions the class hierarchy:

Subclass relationships:

object
    timedelta
    tzinfo
        timezone
    time
    date
        datetime
Related