0

Slightly different question from this one. Are datetime.date objects a subset of datetime.datetime objects? Are there instances when a variable may be both a datetime.date type AND a datetime.datetime object?

Below, I make a datetime.datetime object that also seems to validate as a datetime.date object. Thoughts?

In [1]: import datetime

In [2]: x = datetime.datetime(2013, 7, 13, 13, 0)

In [3]: isinstance(x, datetime.date)
Out[3]: True

In [4]: isinstance(x, datetime.datetime)
Out[4]: True
Community
  • 1
  • 1
Peter
  • 1,065
  • 14
  • 29

1 Answers1

5

Actually datetime.datetime is a subclass of datetime.date.

>>> issubclass(datetime.datetime, datetime.date)
True

So for an instance of datetime.datetime, isinstance(instance, datetime.date) will return True. But it returns False if the two reverse.

>>> date = datetime.date(2011, 1, 1)
>>> isinstance(date, datetime.datetime)
False
>>> 
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
  • Ah ha, thanks @zhangyangyu. (Poor form, but another question)... is there an idiomatic way to distinguish between the two other than what you describe above? – Peter Jul 13 '13 at 15:59
  • Quite sorry I am not an experienced coder and don't know an idiomatic way. But try this `x.__class__ == datetime.datetime` returns `True` and `x.__class__ == datetime.date` returns `False`. @Pete – zhangyangyu Jul 13 '13 at 16:12