Question

The problem is that the isinstance function says that datetime.datetime instances are also instances of datetime.date

Why? That makes sense?

Python 2.7.4 (default, Sep 26 2013, 03:20:26) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> d = datetime.datetime(2014, 4, 30, 15, 9, 4, 218466)
>>> isinstance(d, datetime.datetime)
True
>>> isinstance(d, datetime.date)
True

This makes Django 1.4.10 (I didn't check other versions) to wrongly raise a RuntimeWarning saying that some perfectly timezone aware datetimes are not, since there is a rule (here) that says that date instances are always naive. The warning is raised in django/db/models/fields/init.py, line 759. Maybe this is due to a misunderstanding of the phrase "Objects of the date type are always naive" and they should compare check types using the type function instead of using insinstance (or even better, use the django.utils.timezone.is_aware function).

So is this a Django bug, or the bug is on the behavior of python isinstance function? Or both? Or just me?

>>> from django.utils.timezone import is_aware, utc
>>> d = datetime.datetime(2014, 4, 30).replace(tzinfo=utc)
>>> is_aware(d)
True
>>> isinstance(d, datetime.date)
True
Was it helpful?

Solution

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

datetime is a subclass of date, so all datetimes are also dates.

I'm not sure what the deal is what Django. It would make sense to say that all dates that are not also datetimes are naive, but I'm not sure if that's what it actually does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top