sql - Postgres - 将日期从一种格式转换为另一种格式

标签 sql postgresql

问题本身被问了很多次,但我碰巧遇到了一个我无法解决的问题。

我有一个包含日期格式的表格:Tue Jan 29 15:24:20 CET 2019 根据 documentation 中的字段代表 Dy Mon DD HH24:MI:SS TZ YYYY

updated 表中的列是 text

的类型

我想更新每一行并将此日期转换为 YYYY-MM-DD HH24:MI:SS 但首先我想将日期从一种格式转换为另一种格式但是我得到了 sql错误:

select to_char(to_date(updated, 'Dy Mon DD HH24:MI:SS TZ YYYY'), 'YYYY-MM-DD HH24:MI:SS') from audit where id =1267;
ERROR:  formatting field "TZ" is only supported in to_char

谁能告诉我怎么做?

最佳答案

您的代码的一个问题是 to_date 仅返回一个 date(没有时间)。 to_timestamp 会更合适。

但即便如此,文档也说:

TZ - upper case time-zone abbreviation (only supported in to_char)

但是文档还说:

Tip:
to_timestamp and to_date exist to handle input formats that cannot be converted by simple casting. For most standard date/time formats, simply casting the source string to the required data type works, and is much easier.

所以你应该做的是使用强制转换:

cast(updated as timestamp with time zone)

或者,如果您想忽略时区:

cast(updated as timestamp)

关于sql - Postgres - 将日期从一种格式转换为另一种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685836/

相关文章:

Mysql 存储过程不返回 VARCHAR 输出参数

mysql - MySQL 创建函数中的语法错误

python - django shell 触发 Postgres 空闲事务问题

mongodb - 如何从postgres中的mongodb objectid中提取时间戳

postgresql - 从 Spark/pyspark 连接到 PostgreSQL

sql - 为什么 PostgreSQL 查询在第一个新连接后的第一个请求中比在后续请求中慢?

sql - 连接表或从多个表中选择

mysql - 仅当在其他表中找到时才返回 mysql 结果集

sql - 在 Redshift 中创建 View 时选择列名称

postgresql - Postgres : Error when using COPY from a CSV with timestamptz type