datetime as subclass of date

Skip Montanaro skip at pobox.com
Thu Jan 23 09:16:42 EST 2014


This took my by surprise just now:

>>> import datetime
>>> now = datetime.datetime.now()
>>> isinstance(now, datetime.datetime)
True
>>> isinstance(now, datetime.time)
False
>>> isinstance(now, datetime.date)
True
>>> issubclass(datetime.datetime, datetime.date)
True

I'd never paid any attention to the relationship between the datetime,
time, and date classes of the datetime module before now, but have an
application where, for backwards compatibility, date objects must be
mapped to datetime objects with a time of midnight. That wasn't
working, because I was asking if a datetime instance was an instance
of a date. Which, it turns out, it is.

Skip



More information about the Python-list mailing list