Wic*_*man 151 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)
Run Code Online (Sandbox Code Playgroud)
与使用列的当前时间戳一样:
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)
Run Code Online (Sandbox Code Playgroud)
但那使用当地时间.尝试将其强制为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...
Run Code Online (Sandbox Code Playgroud)
Dan*_*ité 270
甚至不需要功能.只需在默认表达式周围加上括号:
create temporary table test(
id int,
ts timestamp without time zone default (now() at time zone 'utc')
);
Run Code Online (Sandbox Code Playgroud)
Den*_*rdy 25
把它包裹在一个函数中:
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()
);
Run Code Online (Sandbox Code Playgroud)
Ris*_*nha 16
关于什么
now()::timestamp
Run Code Online (Sandbox Code Playgroud)
如果您的其他时间戳没有时区,则此强制转换将为当前时间生成匹配类型"无时区的时间戳".
不过,我想了解别人对这个选项的看法.我仍然不相信我对这个"有/无"时区的理解.
(下面的代码,你应该取代'UTC'的区和now()用于时间戳)
timestamp AT TIME ZONE zone -符合SQL标准timezone(zone, timestamp) -更具可读性函数timezone(zone,timestamp)等效于符合SQL的构造时间戳AT TIME ZONE区域。
'UTC')或间隔(例如INTERVAL '-08:00')-这是所有可用时区的列表now()返回一个timestamp类型的值(正是我们需要的值),并附加了数据库的默认时区(例如2018-11-11T12:07:22.3+05:00)。timezone('UTC', now())将当前时间(带有时区的timestamp类型的时间)转换为的无时区等效项UTC。SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC'将返回2020-03-16T20:00:00Z。文件:timezone()
| 归档时间: |
|
| 查看次数: |
121596 次 |
| 最近记录: |