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
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