1

I'm looking for a way to save datetimes with a specific timezone other than the established timezone, however I have the following settings:

TIME_ZONE = "UTC"

USE_TZ = True

This is convenient, since for the most part I want dates to be saved in UTC, however sometimes I need to keep track of the local datetimes the user setup. Anyone has any idea how to save a datetime without being converted to the default timezone (UTC)?

I am using PostgreSQL, so I don't know if this is possible...

Any tips are welcome.

Ren
  • 4,594
  • 9
  • 33
  • 61

1 Answers1

0

Watch out from storing dates with their timezone in database systems, as there are way too many years of questionable implementations piled up everywhere, from the engines themselves, thought the clients, to the various third party libraries (including the Django ORM).

For example, from the Postgres documentation:

All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the TimeZone configuration parameter before being displayed to the client.

This means that if you save a datetime localized on timezone "Europe/Rome" from Django, with a client setup to use timezone "America/New_York" and then you read it with a client configured with timezone "Europe/London" you will get the British time corresponding to the original datetime, no matter what.

The only reliable way that I found for dealing with time zones using database systems is to save the timezone separately. For example, in a "timezone" filed of the user profile, or using a combination of a "timestamp" + "timezone" fields if storing events which are somehow sensitive to the timezone (i.e. logins, sensor readings, etc.).

In this way you can store all timestamps in UTC (which is what Postgres will do in any case anyway), and then localize them in your application once they are out from the database, which is much clearer, robust, and database-system independent.

Note that if you want to filer your timestamps (i.e. from, to) you will need to perform the queries on UTC, and if you want use time math (i.e. all logins of user X on mondays on timezone "America/New_York") it is going to be a pain in any scenario (you can get a taste here: PostgreSQL date() with timezone).

sarusso
  • 654
  • 5
  • 10