将列类型从int或bigint更改为时间戳

时间:2016-12-15 00:33:48

标签: mysql postgresql

我目前有一个带有时间戳的bigint,而不是我希望更改为标准的“timestamp”列类型。

使用:

ALTER TABLE groupgps ALTER COLUMN date_stamp TYPE timestamp

我明白了:

column "date_stamp" cannot be cast automatically to type timestamp without time zone

使用:

ALTER TABLE groupgps ALTER COLUMN date_stamp TYPE timestamp with time zone USING date_stamp::timestamp with time zone

我明白了:

cannot cast type bigint to timestamp with time zone

除了从头开始重新制作表格之外真的不知所措,但我相信在删除它之前我需要重新创建所有索引以及引用该表的任何内容。

2 个答案:

答案 0 :(得分:1)

ALTER ... USING声明。

从您的样本中测试数据。

CREATE TABLE groupgps AS
SELECT date_stamp::bigint
FROM generate_series(1,100) AS date_stamp;

使用to_timestamp()

您似乎也可以使用to_timestamp功能。 The docs pointing to to_timestamp声称这个,

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720.12 * INTERVAL '1 second';

The to_timestamp function encapsulates the above conversion.

所以我们也可以在我们的ALTER TABLE ... USING中使用它,

ALTER TABLE groupgps
    ALTER COLUMN date_stamp SET DATA TYPE timestamp with time zone
    USING to_timestamp(date_stamp);

不使用to_timestamp()

然后我们调整the docs的例子。

ALTER TABLE groupgps
    ALTER COLUMN date_stamp SET DATA TYPE timestamp with time zone
    USING
        timestamp with time zone 'epoch' + date_stamp * interval '1 second';

答案 1 :(得分:0)

我不相信在Postgres中有biginttimestamp的直接演员。但是,您可以创建一个新的timestamp列,并使用bigint列填充该文章。

ALTER TABLE groupgps ADD COLUMN time_stamp timestamp with time zone;
UPDATE groupgps
SET time_stamp = '1970-01-01 00:00:00 GMT'::timestamp +
                 ((date_stamp)::text)::interval;

参考:https://www.postgresql.org/message-id/200207251134.16658.dev@archonet.com