Usar la hora actual en UTC como valor predeterminado en PostgreSQL

Resuelto Wichert Akkerman asked hace 11 años • 6 respuestas

Tengo una columna de este TIMESTAMP WITHOUT TIME ZONEtipo y me gustaría que el valor predeterminado sea la hora actual en UTC. Obtener la hora actual en UTC es fácil:

postgres=# select now() at time zone 'utc';
          timezone          
----------------------------
 2013-05-17 12:52:51.337466
(1 row)

Como lo es usar la marca de tiempo actual para una columna:

postgres=# create temporary table test(id int, ts timestamp without time zone default current_timestamp);
CREATE TABLE
postgres=# insert into test values (1) returning ts;
             ts             
----------------------------
 2013-05-17 14:54:33.072725
(1 row)

Pero eso usa la hora local. Intentar forzar eso a UTC da como resultado un error de sintaxis:

postgres=# create temporary table test(id int, ts timestamp without time zone default now() at time zone 'utc');
ERROR:  syntax error at or near "at"
LINE 1: ...int, ts timestamp without time zone default now() at time zo...
Wichert Akkerman avatar May 17 '13 20:05 Wichert Akkerman
Aceptado

Ni siquiera se necesita una función. Simplemente ponga paréntesis alrededor de la expresión predeterminada:

create temporary table test(
    id int, 
    ts timestamp without time zone default (now() at time zone 'utc')
);
Daniel Vérité avatar May 17 '2013 13:05 Daniel Vérité

Otra solución más:

timezone('utc', now())
martti avatar Jan 05 '2018 19:01 martti

Envuélvelo en una función:

create function now_utc() returns timestamp as $$
  select now() at time zone 'utc';
$$ language sql;

create temporary table test(
  id int,
  ts timestamp without time zone default now_utc()
);
Denis de Bernardy avatar May 17 '2013 13:05 Denis de Bernardy