postgresql - 使用 UTC 中的当前时间作为 PostgreSQL 中的默认值

标签 postgresql timezone timestamp

我有一个类型为 TIMESTAMP WITHOUT TIME ZONE 的列,并且希望将该列默认为 UTC 中的当前时间。获取 UTC 的当前时间很容易:

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

使用列的当前时间戳:

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)

但那使用本地时间。试图将其强制为 UTC 会导致语法错误:

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...

最佳答案

甚至不需要函数。只需在默认表达式两边加上括号:

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

关于postgresql - 使用 UTC 中的当前时间作为 PostgreSQL 中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16609724/

相关文章:

ios - 第二个 bug 的 CLLocation 时间戳分数?

sqlite - GROUP BY 时间戳值范围

postgresql - 如果将时间戳转换为日期,Postgres 是否使用索引?

database - 如何在 Kubernetes Pod 中运行的 PostgreSQL 中启用流式复制?

python - 如果我使用 psycopg2,如何返回字典或 json?

java - 如何获得缩写时区?

ruby-on-rails - 在 9 :00 AM in their Local Time Zone 向用户发送时事通讯

php - Symfony2 和 date_default_timezone_get() - 依赖系统的时区设置是不安全的

postgresql - Postgres : incorrect sorting if timestamp in smtp format

ruby-on-rails - 从 DBeaver 连接到 Docker 容器中的 PostgreSQL 数据库