[Django]-How django time zone works with model.field's auto_now_add

39👍

Use timezone utils of django

from django.utils import timezone
date_generated = models.DateTimeField(default=timezone.now)

25👍

The problem is on your end: datetime.now() is not TZ aware, so you’re the one feeding in a naive TZ. See the Django docs on this issue. The reason it works when setting default=datetime.now is that you’re forcing the value to a naive datetime, so when you later compare it with another naive datetime, there’s no problem.

You need to get “now” the following way:

import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)

10👍

Be careful setting a DateTimeField default value of datetime.now(), as that will compute a single value when Apache/nginx loads Django (or when you start the development server), and all subsequent records will receive that value.

Always use auto_now_add for that reason.

Leave a comment