How to best store a timestamp in PostgreSQL?
Store timestamps as timestamp
, or rather timestamptz
(timestamp with time zone
) since you are dealing with multiple time zones. That enforces valid data and is typically most efficient. Be sure to understand the data type, there are some misconceptions floating around:
- Time zone storage in PostgreSQL timestamps
- Ignoring timezones altogether in Rails and PostgreSQL
To address your concern:
passing a correctly formatted timestamp is more complex than a simple number
You can pass and retrieve a UNIX epoch either way if you prefer:
SELECT to_timestamp(1437346800)
, extract(epoch FROM timestamptz '2015-07-20 01:00+02');
Related:
- Truncate timestamp to arbitrary intervals
- Aggregating (x,y) coordinate point clouds in PostgreSQL
If you want to store the current timestamp with writes to the DB, use a timestamptz
column with default value now()
. The system time on the DB server is typically much more reliable and consistent than multiple clients handing in their respective notion of what time it is.
For INSERT
it can be as simple as:
CREATE TABLE foo (
... -- other columns
, created_at timestamptz NOT NULL DEFAULT now()
);
And just don't write to that column. It's filled in automatically.
You should always store data in its native data type so you can use the built-in functions. The data type of a timestamp is: timestamp
.
As an aside, a timestamp
is not stored as a string, it's stored as an 8-byte integer, exactly the same as bigint
: PostgreSQL documentation.