Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeField received a naive datetime

I have model with DateTimeField column.

I'm try to insert row with database current_time value directly into table by sql query.

My sql query for MySQL database like:

INSERT INTO MyTable (..., my_datetime, ...) VALUES (..., current_time, ...)

And get:

RuntimeWarning: DateTimeField ModelName.field_name received a naive datetime (2014-01-09 22:16:23) while time zone support is active.

How to insert current time directly into table by sql query without warning?

like image 344
DoNotArrestMe Avatar asked Jan 10 '14 07:01

DoNotArrestMe


3 Answers

Further to falsetru's answer, if the datetime has already been created you can convert it to timezone aware:

from django.utils import timezone
my_datetime = timezone.make_aware(my_datetime, timezone.get_current_timezone())
like image 139
hellsgate Avatar answered Oct 05 '22 08:10

hellsgate


Use django.utils.timezone.now instead of datetime.datetime.now.

from django.utils import timezone
current_time = timezone.now()
like image 35
falsetru Avatar answered Oct 05 '22 07:10

falsetru


You can also make the datetime time zone aware with localize from pytz, as explained here.

UTC:

import pytz
dt_aware = pytz.utc.localize(dt_naive)

Any other time zone:

import pytz
tz = 'Europe/Berlin' #or whaterver timezone you want
dt_aware = pytz.timezone(tz).localize(dt_naive)

And here the list of timezones.

like image 30
J0ANMM Avatar answered Oct 05 '22 07:10

J0ANMM