Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeWarning: DateTimeField received a naive datetime

I m trying to send a simple mail using IPython. I have not set up any models still getting this error. What can be done?

Error : /home/sourabh/Django/learn/local/lib/python2.7/site-packages/django/db/models/fields/init.py:827: RuntimeWarning: DateTimeField received a naive datetime (2013-09-04 14:14:13.698105) while time zone support is active. RuntimeWarning)

Tried : The first step is to add USE_TZ = True to your settings file and install pytz (if possible).

Error changed:

(learn)sourabh@sL:~/Django/learn/event$ python manage.py shell /home/sourabh/Django/learn/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:53: RuntimeWarning: SQLite received a naive datetime (2013-09-05 00:59:32.181872) while time zone support is active.   RuntimeWarning) 
like image 207
shifu Avatar asked Sep 04 '13 19:09

shifu


2 Answers

The problem is not in Django settings, but in the date passed to the model. Here's how a timezone-aware object looks like:

>>> from django.utils import timezone >>> import pytz >>> timezone.now() datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC) 

And here's a naive object:

>>> from datetime import datetime >>> datetime.now() datetime.datetime(2013, 11, 20, 20, 9, 26, 423063) 

So if you are passing email date anywhere (and it eventually gets to some model), just use Django's now(). If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.

like image 167
kravietz Avatar answered Sep 21 '22 17:09

kravietz


Use django.utils.timezone.make_aware function to make your naive datetime objects timezone aware and avoid those warnings.

It converts naive datetime object (without timezone info) to the one that has timezone info (using timezone specified in your django settings if you don't specify it explicitly as a second argument):

import datetime from django.conf import settings from django.utils.timezone import make_aware  naive_datetime = datetime.datetime.now() naive_datetime.tzinfo  # None  settings.TIME_ZONE  # 'UTC' aware_datetime = make_aware(naive_datetime) aware_datetime.tzinfo  # <UTC> 
like image 34
dmrz Avatar answered Sep 18 '22 17:09

dmrz