How should I store my “dates + times” in a PostgreSQL database?
This is what I want to achieve:
- How can I have all the entries that occurred on (for example) 1 January 2012 00:00:00 local time anywhere in the world?
- Display all the entries sorted by date according to UTC time. (2012 New Year Eve in New York is more recent than the New Year in London).
How should I store my data? I have read that PostgreSQL stores all time in UTC internally (PostgreSQL documentation), so my users timezone is in fact lost.
I think I should use one column with type “timestamp without timezone”:
- Point 1 is easy.
- And with another column of type “String” I will store the timezone string (e.g : America/New_York)
but then, point 2 seems still hard to do ….
I hope I am clear.
Edit new idea: I think with storing two timestamps: one without timezone (1. ok) and one with timezone (2. ok)
Yes, PostgreSQL stores all timestamps as UTC internally. For a
timestamp with time zonethe time zone offset is only applied to adjust the time to UTC, but is not stored explicitly.I would not store the timezone string or even less a time zone abbreviation (those are not precise). This can later require expensive computation, because you have to consider daylight savings time and other oddities of the international time regime.
You can either store the time zone offset as interval (takes 12 bytes) or a numerical amount of seconds (takes 4 bytes as integer) like I demonstrate in this related answer.
Or, like you already proposed: store the local timestamp in addition to the UTC timestamp (takes 8 bytes). That would make your tasks easy. Consider the following demo::
Query for question 1:
Query for question 2:
The tricky part with this solution may be to enter the local timestamp. That’s easy as long as all data is entered locally. But it needs consideration if you enter data for, say, New York in Los Angeles. Use the
AT TIME ZONEconstruct for that:Note how I use a timestamp with time zone as input.
AT TIME ZONEgives different results for timestamps with or without time zone.