DateTimeField received a naive datetime

Introduction: While doing some djangos stuff recently, a DateTimeField in a table has a field of type DateTimeField. When importing a DateTimeField, an error is reported: RuntimeWarning: DateTimeField Artical.create_time received a naive datetime.

The cause of

At first, I thought it was just a warning. I just wanted to let…. go However, I took a good look at the database and found that the time inserted into the database was not the same as the current time.

I started with datetime.datetime.today() and the output was the same as the current time but it gave me a warning. I thought it was ok and the time was right, but I was curious and googled it.

Found the problem

After baidu, I read a blog of an unknown netizen and learned that django has some time reading and storage inconsistencies.

Here’s how it works: after django1.4, there are two concepts: naive time and active time. Simply put, naive Time is time without a time zone, while related Active time is time with a time zone. For example, datetime.datetime.utcnow(), datetime.datetime.now() output similar to 2015-05-11 09:10:33.080451 is naive time without a time zone. When django.util. Timezone.now () is used, the time like 2015-05-11 09:05:19.936835+00:00 is Active time, where +00:00 indicates relative timezone.

The reason:

Django stores after version 1.4. If USE_TZ=True is set, the time stored in the database is always UTC. If you set USE_TZ=True and TIME_ZONE = ‘UTC’ in your Settings, django will store the time in its database as if it were UTC, if you use datetime.datetime.now(). This causes it to convert the current time to UTC (that is, add 8 hours) and read it directly to UTC, which is why many people on the Internet encounter times stored in the database that are 8 hours faster than local time.

To solve the problem

With that knowledge, it’s easy to solve the problem just to understand why, and then the solution. USE_TZ=True; TIME_ZONE = ‘Asia/Shanghai’; datetime.datetime.now(); The fetching time is the same as the local time.

And then I had this weird problem… Multiple submissions get the same time??

Ok, this problem is caused by my own outrageous operation.. I set the default value of the database time field todatetime.now(). This results in the same data for subsequent inserts. (Here’s a reminder not to do this…)

The default value is TIME_ZONE = ‘Asia/Shanghai’. The default value is TIME_ZONE = ‘Asia/Shanghai’. The default value is ‘Asia/Shanghai’.

To prevent this from happening, we’ll use Django’s default timezone.now() function.

Change it to timezone.now() and the warning disappears. Timezone. now() : if USE_TZ=True in the setting, the output time is naive UTC time. If USE_TZ=False in the setting, the output time is not with the timezone.

Here is a comparison of the time output with the two Settings:

2.False:

The end:

At this point there should be no problems, then the end of the flower.