PostgreSQL改变没有时区的类型时间戳 - >带时区

gyo*_*ham 55 postgresql timezone

问题很简单:如果我已经在没有时区的列类型时间戳中有数据,如果我将类型设置为带时区的时间戳,postgresql对这些数据做了什么?

dbe*_*hur 54

它将当前值保持在本地时间,并将时区设置为本地时间的偏移量:

create table a(t timestamp without time zone, t2 timestamp with time zone);
insert into a(t) values ('2012-03-01'::timestamp);
update a set t2 = t;
select * from a;
          t          |           t2           
---------------------+------------------------
 2012-03-01 00:00:00 | 2012-03-01 00:00:00-08

alter table a alter column t type timestamp with time zone;
select * from a;
           t            |           t2           
------------------------+------------------------
 2012-03-01 00:00:00-08 | 2012-03-01 00:00:00-08
Run Code Online (Sandbox Code Playgroud)

根据Alter Table手册:

如果省略[USING子句],则默认转换与从旧数据类型转换为new的赋值相同.

根据日期/时间类型的手册

之间的转换时间戳没有时区时间戳和时区,通常假设没有时区的时间戳值应取或给出时区的本地时间.可以使用指定不同的时区进行转换AT TIME ZONE.


Ant*_*ala 28

最好明确指定时区.比如说,如果您的时间戳应该是UTC(但没有时区),那么您应该警惕客户端或服务器的时区可能会弄乱这里的所有内容.而是写:

ALTER TABLE a ALTER COLUMN t TYPE TIMESTAMP WITH TIME ZONE USING t AT TIME ZONE 'UTC'
Run Code Online (Sandbox Code Playgroud)