Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: "auto_now_add=True" giving incorrect time

I would like the current time to be recorded automatically when a record is created in my Django database.

In my model I am using:

dateTime = models.DateTimeField(auto_now_add=True)

From my understanding this automatically stamps the time considering the correct time zone. Instead however, this is outputting a time that is 5 hours ahead of my local time.

So to try and debug this, I ran this function in my view and printed the output:

from django.utils import timezone
timeNow =  timezone.localtime(timezone.now())

timeNow will output the correct time.

So I changed my model to:

def get_time():
    return timezone.localtime(timezone.now())

dateTime = models.DateTimeField(default = get_time)

This still results in the same incorrect time stamp.

I also changed the timezone in my settings.py

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Canada/Central'

USE_I18N = True

USE_L10N = True

USE_TZ = True

Any ideas what I am missing?

like image 590
MattG Avatar asked Sep 20 '25 18:09

MattG


1 Answers

From my understanding this automatically stamps the time considering the correct time zone.

That's a misunderstanding. See the first sentence of the timezone documentation:

When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

As you've seen, that UTC datetime can then be converted to whatever you want for display, etc.

like image 101
Kevin Christopher Henry Avatar answered Sep 22 '25 13:09

Kevin Christopher Henry