在PostgreSQL中设置时间戳列的时区 [英] Set timestamp column's timezone in PostgreSQL

查看:596
本文介绍了在PostgreSQL中设置时间戳列的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PostgreSQL表上有一个触发器来更新时间戳字段,但是我想在正确的时区中获取它。如何将我的列默认设置为始终位于 PST中?这是我的触发器:

I have a trigger on a PostgreSQL table that updates a timestamp field, but I want to get it in the right timezone. How can I set my column to always be in 'PST' by default? Here is my trigger:

ALTER TABLE coastal ADD latest_report TIMESTAMP;

ALTER TABLE coastal ALTER COLUMN latest_report 
SET DEFAULT CURRENT_TIMESTAMP;

UPDATE coastal SET latest_report=CURRENT_TIMESTAMP;

CREATE OR REPLACE FUNCTION coastal_latest_report()
  RETURNS TRIGGER AS '
BEGIN
   NEW.latest_report = NOW();
   RETURN NEW;
END;
' LANGUAGE 'plpgsql';

CREATE TRIGGER coastal_latest_report_modtime BEFORE UPDATE
  ON coastal FOR EACH ROW EXECUTE PROCEDURE
  coastal_latest_report();


推荐答案


如何设置

How can I set my column to always be in 'PST' by default?

这是不可能的/引起误解。时间戳记列不在 any 时区中。永远不会保存时区,即使是带有时区的时间戳 timestamptz )也不会保存,这总是节省UTC时间。这个名称有点误导,我给你。

This is not possible / a misunderstanding. A timestamp column is not in any time zone. The time zone is never saved, not even for timestamp with time zone (timestamptz), which always saves UTC time. That name is a tad bit misleading, I'll give you that.

您有两个非常简单的选择:

You have two very simple options:


  • now()保存到 timestamptz 列中

  • now()保存到 timestamp 列中。 (在强制转换中,时区偏移量被截断了。)

  • Save now() to a timestamptz column.
  • Save now() to a timestamp column. (The time zone offset is truncated in the cast.)

如果您希望时间戳为 显示 为 PST时区,请将会话的时区设置设置为该时区(如果尚未设置)。例如:

If you want timestamps to be displayed for the 'PST' time zone, set the time zone setting of your session to that time zone (if it is not set already). For instance:

SET timezone='America/Anchorage'

此相关答案中的详细信息:

Ample details in this related answer:

  • Ignoring timezones altogether in Rails and PostgreSQL

要找到您的时区名称:

  • Set custom timezone in Django/PostgreSQL (Indian Standard Time)

如果要保存输入值的原始时区:

If you want to save the original time zone of input values:

  • Preserve timezone in PostgreSQL timestamptz type

这篇关于在PostgreSQL中设置时间戳列的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆