The PostgreSQL data types would be timestamp
or timestamptz
. But that contradicts what you are doing. You take the epoch value and multiply by 1000. You'd have to save that as bigint
or some numeric type.
Basics:
I would save the value as timestamptz
as is. (No multiplication.) You can always extract ms if need should be.
If you need to translate the Unix epoch value back to a timestamp, use:
SELECT to_timestamp(1352633569.151);
--> timestamptz 2012-11-11 12:32:49.151+01
Just save "now"
If you actually want to save "now", i.e. the current point in time, then let Postgres do it for you. Just make sure the database server has a reliable local time. (Maybe install ntp
on the server.) This is generally more reliable, accurate and simple.
Set the DEFAULT
of the timestamp column to now()
or CURRENT_TIMESTAMP
.
If you want timestamp
instead of timestamptz
you can still use now()
, which is translated to "local" time according to the servers timezone setting - effectively the same as LOCALTIMESTAMP
. Or, to get the time for a given time zone:
now() AT ZIME ZONE 'Europe/Vienna' -- your time zone here
Or, in your particular case, since you seem to want only three fractional digits: now()::timestamp(3)
, or CURRENT_TIMESTAMP(3)
, or CURRENT_TIMESTAMP(3) AT ZIME ZONE 'Europe/Vienna'
, or date_trunc('ms', LOCALTIMESTAMP)
. The latter truncates, while the other ones round. Typically, you want to truncate. See:
Or, if you define the type of the column as timestamp(3)
, all timestamp values are coerced to the type and rounded to 3 fractional decimal digits automatically:
CREATE TABLE tbl (
-- other columns
, ts_column timestamp(3) DEFAULT now()
);
The value is set automatically on INSERT
, you don't even have to mention the column.
If you want to do it ON UPDATE
, add a TRIGGER
like:
Trigger function:
CREATE OR REPLACE FUNCTION trg_up_ts()
RETURNS trigger
LANGUAGE plpgsql AS
$func$
BEGIN
NEW.ts_column := now();
RETURN NEW;
END
$func$
Trigger:
CREATE TRIGGER log_up_ts
BEFORE UPDATE ON tbl
FOR EACH ROW EXECUTE FUNCTION trg_up_ts();
In Postgres 10 or older use the key word PROCEDURE
instead of FUNCTION
. See:
Now, everything works automatically.