Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Django not saving timezone info. How to store this correctly

I've got this code in an ajax view:

    now = pytz.timezone("America/Guayaquil").localize(datetime.now())
    print("HOUR: %s" % now.hour)        
    new_timer = WorkTime.objects.create(inicio=now)
    print("new_timer.id: %s" % new_timer.id)
    print("new_timer.hour %s" % new_timer.inicio.hour)

it prints this:

HOUR: 18
new_timer.id: 16
new_timer.hour 18

"inicio" is a DateTimeField. Then I access the same object from a regular view to render an html, this is the code:

last_timer = TiempoEmpresarial.objects.filter(final__isnull=True).last()
print("Timer object:")
print(last_timer.id)  # is it the same obj?
print(last_timer.inicio.hour)

it prints this:

Timer object:
16
23

It is the same object, id=16. But it has a different hour. Why?

Upvotes: 0

Views: 1093

Answers (2)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

You explicitly create now in the America/Guayaquil timezone, which is 5 hours before UTC.

When you save the model to the database, the DateTimeField is converted to and stored in UTC, as described in the timezone documentation: "When support for time zones is enabled, Django stores datetime information in UTC in the database."

When you later retrieve that value, you get the UTC version, hence the 5-hour difference.

Upvotes: 1

Shaokun
Shaokun

Reputation: 88

Django stores UTC time in the database, when rendering, TIME_ZONE and USE_TZ in setting.py decides the timezone.

In your case, try print(last_timer.inicio), you would see something like datetime.datetime(2019, 12, 17, 3, 17, 6, 760770, tzinfo=<UTC>).

Upvotes: 1

Related Questions