Saving objects to postgresql with DJango in UTC instead of local timezone?

Viewed 18

I have a column in my table called "signed_up_date", which I am using the auto_now_add=True parameter with the DateTimeField() function.

I want this function to save timestamps to the PostgreSQL DB in UTC instead of my local time (EST) which it is currently doing.

Barebones version of the model for quick ref below:

class TutorTest(models.Model):
    signed_up_on = models.DateTimeField(auto_now_add=True)

Settings.py

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

I thought based on the docs, if I have Time_Zone set to UTC and UTC_TZ set to True, then the default behavior of Django would be to save as UTC.

I know when I check postgresql timezone I get:

SHOW TIMEZONE;
  TimeZone
------------
 US/Eastern
(1 row)

I just tried a new model with timezone.now() and it looks like in the db shell I get:

datetime.datetime(2022, 9, 21, 14, 36, 16, 670726, tzinfo=datetime.timezone.utc)

But the db saved it as:

2022-09-21 10:35:26.633116-04

I guess it's the DB in this situation? Confused lol

*** EDIT *** I think I figured it out. The database takes a UTC time and converts to EST, but when I pull the time out django reads it as UTC. Which works for me lol.

1 Answers

The timestamp which is actually saved in the database would be in UTC, but if you are using some sort of tool such as DBeaver (for example) to look into and query the datbase, then that tool would convert the timestamps as per what is put in its configuration and show those converted timestamps to you. But the underlying data in the database is still in UTC.

Hope this helps.

Related