Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using current time in UTC as default value in PostgreSQL

People also ask

How do I get the UTC timestamp in PostgreSQL?

timezone('UTC', now()) turns our current time (of type timestamp with time zone) into the timezonless equivalent in UTC . E.g., SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC' will return 2020-03-16T20:00:00Z .

Is Postgres now () in UTC?

PostgreSQL stores the timestamptz in UTC value.

What is the default timestamp PostgreSQL?

Explanation: The above example shows the time and timestamp of all three functions working is the same. The current timestamp is basically used as the default timestamp value of a column in PostgreSQL.


A function is not even needed. Just put parentheses around the default expression:

create temporary table test(
    id int, 
    ts timestamp without time zone default (now() at time zone 'utc')
);

Still another solution:

timezone('utc', now())

Wrap it in a function:

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()
);

What about

now()::timestamp

If your other timestamp are without time zone then this cast will yield the matching type "timestamp without time zone" for the current time.

I would like to read what others think about that option, though. I still don't trust in my understanding of this "with/without" time zone stuff.

EDIT: Adding Michael Ekoka's comment here because it clarifies an important point:

Caveat. The question is about generating default timestamp in UTC for a timestamp column that happens to not store the time zone (perhaps because there's no need to store the time zone if you know that all your timestamps share the same). What your solution does is to generate a local timestamp (which for most people will not necessarily be set to UTC) and store it as a naive timestamp (one that does not specify its time zone).