【问题标题】:Alter column type from int or bigint to timestamp将列类型从 int 或 bigint 更改为时间戳
【发布时间】:2016-12-15 00:33:48
【问题描述】:

我目前有一个以毫秒为单位的时间戳的 bigint,但我想更改为标准的“时间戳”列类型。

使用:

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

除了从头开始重新制作表格之外,我真的很茫然,但我相信我需要在删除之前重新创建所有索引和引用该表​​格的任何内容。

【问题讨论】:

标签: mysql postgresql


【解决方案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';

【讨论】:

  • 是的,就是这样。实际上,我在发布后不久就设法弄清楚了——一如既往——我专门使用了你提到的 (USING to_timestamp()),所以无论如何我都会将此标记为答案。谢谢!
【解决方案2】:

我不相信 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

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    相关资源
    最近更新 更多