2017-05-26 150 views
-1

我想在几个表中的UTC时间戳“创建”字段。Postgres UTC时间戳?

ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),给我的本地时间与时区:

foo=# select ts from messages; 
       ts    
------------------------------- 
2017-05-26 11:54:07.532796+01 
2017-05-26 11:54:08.536241+01 
2017-05-26 11:54:09.538119+01 
2017-05-26 11:54:10.541089+01 
2017-05-26 11:54:11.543262+01 

ts TIMESTAMP NOT NULL DEFAULT now(),给我本地时间没有时区信息(危险):

foo=# select ts from messages; 
      ts    
---------------------------- 
2017-05-26 11:56:00.134596 
2017-05-26 11:56:01.13798 
2017-05-26 11:56:02.140586 
2017-05-26 11:56:03.143076 
2017-05-26 11:56:04.14565 

什么字段定义会给我下面,当代码在非UTC时区(例如BST,英国夏令时)的服务器上运行时:

foo=# select ts from messages; 
      ts    
---------------------------- 
2017-05-26 10:56:00.134596+00 
2017-05-26 10:56:01.13798+00 
2017-05-26 10:56:02.140586+00 
2017-05-26 10:56:03.143076+00 
2017-05-26 10:56:04.14565+00 

连:

foo=# select ts from messages; 
      ts    
---------------------------- 
2017-05-26 10:56:00.134596 
2017-05-26 10:56:01.13798 
2017-05-26 10:56:02.140586 
2017-05-26 10:56:03.143076 
2017-05-26 10:56:04.14565 

就可以了,如果不出意外是可能的(注:时间为上午10点UTC,不是上午11点BST在这两个例子以上)。

+1

timestamptz会做。您的客户端时区将运行时间,该时间值将转换为UTC并保存到服务器。 postgres以UTC格式保存所有时间戳 –

回答

2

时间戳和时区是你的选择:

t=# select now(); 
       now 
------------------------------- 
2017-05-26 11:04:19.240294+00 
(1 row) 

t=# set timezone to 'EET'; 
SET 
t=# select now(); 
       now 
------------------------------- 
2017-05-26 14:04:45.749123+03 
(1 row) 

,但如果你现在插入选择(),它会保存在UTC时间,你可以检查:

t=# select now() at time zone 'utc'; 
      timezone 
---------------------------- 
2017-05-26 11:05:01.045544 
(1 row) 

https://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONES

所有支持时区的日期和时间均以UTC格式存储在内部。在显示给客户端之前,它们将 转换为由TimeZone 配置参数指定的区域中的本地时间。

+0

再次感谢。我并不了解Postgres正在给客户端(客户端)本地化的时间,而不是存储本地化的时间。 – fadedbee