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

我在下面try 了多种方法,但仍然找不到正确的方法.希望你能帮助我.

当然,如果我的问题得到解决,我可以建一张新桌子.

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

推荐答案

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

-- 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;

Postgresql相关问答推荐

PostgreSQL中btree_gist索引涉及integer和tstzrange属性查询计划的问题

无法从Docker迁移Golang上的两个不同服务到一个数据库'

一列引用两个不同的表

为什么Postgres优化器切换到嵌套循环进行连接?

将XML解析从T-SQL迁移到Postgres时出现问题

Ubuntu 上的 PostgreSQL 安装:找不到initdb命令

合并两个字典并创建一个包含更新凭据的字典列表

AGE Graph 实际上存储为 postgreSQL 表,对吧?如何检索该表(不是图表)?

如何在typeorm和嵌套js中将运行时变量设置为postgresql

连接 Supbase Postgresql 数据库时,Stepzen Graphiql 资源管理器中的主机名解析错误

我可以使用 Rails 将数组存储在 hstore 中吗

并发刷新materialized视图

PostgreSQL 可以对数组元素有唯一性约束吗?

如何使用字符串作为 PostgreSQL 咨询锁的键?

判断值是否存在于列中

在 PostgreSQL 中显示正在运行的查询的全文

Postgres - 如果找不到记录,则在更新时返回错误

Postgres NOT IN (null) 没有结果

如何在 PostgreSQL 中插入多行

docker postgres 无法从指定端口启动