postgreSQL 将列数据类型更改为没有时区的时间戳

新手上路,请多包涵

我想将一列数据从文本更改为类型时间戳。我的数据中没有时区。我的数据格式是 28-03-17 17:22,包括时间和日期,但没有时区。换句话说,我所有的数据都在同一个时区。我该怎么做?

我在下面尝试了多种方法,但我仍然找不到正确的方法。希望您能够帮助我。

当然,如果我的麻烦可以解决,我可以建立一个新表。

 alter table AB
alter create_time type TIMESTAMP;

ERROR:  column "create_time" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify "USING create_time::timestamp without time zone".
********** Error **********

ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
SQL state: 42804
Hint: You might need to specify "USING create_time::timestamp without time zone".

 alter table AB
alter create_time type TIMESTAMP without time zone;

ERROR:  column "create_time" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify "USING create_time::timestamp without time zone".
********** Error **********

ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
SQL state: 42804
Hint: You might need to specify "USING create_time::timestamp without time zone".

 alter table AB
alter create_time::without time zone type TIMESTAMP;

ERROR:  syntax error at or near "::"
LINE 2:  alter create_time::without time zone type TIMESTAM
                          ^
********** Error **********

ERROR: syntax error at or near "::"
SQL state: 42601
Character: 50

 alter table AB
alter create_time UTC type TIMESTAMP;

ERROR:  syntax error at or near "UTC"
LINE 2: alter create_time UTC type TIMESTAMP;
                          ^
********** Error **********

ERROR: syntax error at or near "UTC"
SQL state: 42601
Character: 50

原文由 Amy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

如果 create_time 是具有有效日期值的 TEXT 类型,则进行如下更改会更容易(建议先进行表转储作为备份):

 -- Create a temporary TIMESTAMP column
ALTER TABLE AB ADD COLUMN create_time_holder TIMESTAMP without time zone NULL;

-- Copy casted value over to the temporary column
UPDATE AB SET create_time_holder = create_time::TIMESTAMP;

-- Modify original column using the temporary column
ALTER TABLE AB ALTER COLUMN create_time TYPE TIMESTAMP without time zone USING create_time_holder;

-- Drop the temporary column (after examining altered column values)
ALTER TABLE AB DROP COLUMN create_time_holder;

原文由 Leo C 发布,翻译遵循 CC BY-SA 3.0 许可协议

您没有指定 create_time 的原始类型,所以我假设它是带时区的 TIME(因为在尝试更改为不带时区的 TIMESTAMP 时,带时区的类型 DATE 或 TIMESTAMP 不应给出上述错误)。由于 TIMESTAMP 除了 TIME 之外还有日期信息,因此您需要在 ALTER 语句中补充日期信息,例如:

 ALTER TABLE AB ALTER COLUMN create_time TYPE TIMESTAMP without time zone USING date('20170327') + create_time;

如果您有相应的 DATE 列(例如 create_date),则可以将其传递给 date() 函数,例如:

 ALTER TABLE AB ALTER COLUMN create_time TYPE TIMESTAMP without time zone USING date(create_date) + create_time;

原文由 Leo C 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进