【问题标题】:PostgreSQL select now()::timestamp differs from default now()::timestampPostgreSQL select now()::timestamp 不同于默认 now()::timestamp
【发布时间】:2019-05-02 07:15:57
【问题描述】:

在我的程序中,每个表都有一列last_modified

last_modified int8 DEFAULT (date_part('epoch'::text, now()::timestamp) * (1000)::double precision) NOT NULL

为了更新,我添加了一个触发器:

CREATE OR REPLACE FUNCTION sync_lastmodified() RETURNS trigger AS $$
BEGIN
  NEW.last_modified := (date_part('epoch'::text, now()::timestamp) * (1000)::double precision);

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER
  sync_lastmodified
BEFORE UPDATE ON
  ourtable
FOR EACH ROW EXECUTE PROCEDURE
  sync_lastmodified();

他们应该将当前时间作为长值写入更新/插入时的last_modified 列。 但是,它并没有像我预期的那样工作。

为了重现该问题,我进行了更新并得到以下信息:

last_modified value equals 1543576224455 (Friday November 30, 2018 16:10:24 (pm) in time zone Asia/Tashkent (+05))

几乎同时我从 pgAdmin 运行函数 now

SELECT now()

得到了结果:

2018-11-30 11:10:36.891426+05

为了在几秒钟内检查系统时间,我从终端运行 timedatectl status 并得到以下结果:

问题是为什么函数 now() 给出的时间是 5 小时 当我从触发器运行它或作为默认值时的区别 插入?

【问题讨论】:

  • 由于这个问题,我在根据 last_modified 时间选择值时得到错误的结果。

标签: postgresql timestamp utc current-time


【解决方案1】:

epoch 将为您提供自纪元以来的秒数。正如the documentation 所说:

epoch

对于 timestamp with time zone 值,自 1970-01-01 00:00:00 UTC 以来的秒数(可以为负数)

由于您与 UTC 相差 5 小时,这就解释了差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2016-06-27
    • 2015-05-02
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 2013-12-29
    相关资源
    最近更新 更多