【问题标题】:Update multiple Postgres timestamps更新多个 Postgres 时间戳
【发布时间】:2022-11-30 14:12:29
【问题描述】:

我正在尝试使用以下查询更新 Postgres 12 中数百个对象的时间戳:

UPDATE foo_bar AS c SET
created_at = c2.created_at
FROM (VALUES
    (101, '2021-09-27 14:54:00.0+00'),
    (153, '2021-06-02 14:54:00.0+00')
) as c2(id, created_at)
WHERE c.id = c2.id;

其中 created_at 代表一个 dateTimeField:

created_at = models.DateTimeField(auto_now_add=True)

我收到以下错误:

ERROR:  column "created_at" is of type timestamp with time zone but expression is of type text

我尝试了 created_at 值的多种变体,但均无济于事。知道为什么这不起作用吗?

【问题讨论】:

  • Postgres 似乎在读取日期时间字符串时遇到问题。您是否尝试过ISO 8601 格式?例如2021-09-27T14:54:00.000+0000 还是使用真正的 DateTime 对象而不是字符串?
  • 您的值被转换为文本,您必须使用 CAST() 将其显式转换为时间戳
  • 将第一个值转换为时间戳:VALUES (101, '2021-09-27 14:54:00.0+00'::timestamptz), (....)
  • @a_horse_with_no_name 成功了!如果您愿意,请随时添加答案,我会将其标记为正确。

标签: django postgresql


【解决方案1】:

感谢@a_horse_with_no_name 的回答。我不得不将这些值转换为带有时区的时间戳,如下所示:

UPDATE foo_bar AS c SET
created_at = c2.created_at
FROM (VALUES
    (101, '2021-09-27 14:54:00.0+00::timestamptz'),
    (153, '2021-06-02 14:54:00.0+00::timestamptz')
) as c2(id, created_at)
WHERE c.id = c2.id;

解释转换工作原理的 Postgres 文档 (link):

强制转换指定如何在两种数据类型之间执行转换

默认情况下,只能通过显式转换请求调用转换,即显式 CAST(x AS typename) 或 x::typename 构造。

解释timestamptz (link) 的 Postgres 文档:

timestamptz 被接受为 timestamp with time zone 的缩写

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2021-07-26
    • 2020-07-30
    • 2013-01-14
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多