使用 UTC 中的当前时间作为 PostgreSQL 中的默认值 [英] Using current time in UTC as default value in PostgreSQL
本文介绍了使用 UTC 中的当前时间作为 PostgreSQL 中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一列 TIMESTAMP WITHOUT TIME ZONE
类型,并希望将其默认设置为 UTC 中的当前时间.以 UTC 格式获取当前时间很容易:
I have a column of the TIMESTAMP WITHOUT TIME ZONE
type and would like to have that default to the current time in UTC. Getting the current time in UTC is easy:
postgres=# select now() at time zone 'utc';
timezone
----------------------------
2013-05-17 12:52:51.337466
(1 row)
就像使用列的当前时间戳一样:
As is using the current timestamp for a column:
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 会导致语法错误:
But that uses local time. Trying to force that to UTC results in a syntax error:
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...
推荐答案
甚至不需要一个函数.只需在默认表达式周围加上括号:
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')
);
这篇关于使用 UTC 中的当前时间作为 PostgreSQL 中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文