让我们说我们有一个Postgres表:
CREATE TABLE public.observations (
id integer NOT NULL,
utc_created_at timestamp without time zone NOT NULL
)
如果我们想对在某个UTC日期进行的观察计数感兴趣,我们可以:
SELECT COUNT(observations.id),
DATE(utc_created_at) AS date_utc_created_at
GROUP BY DATE(date_utc_created_at);
但是,现在让我们说,我想按太平洋标准时间将观察结果分组。有没有一种方法可以不更改架构?
如果没有办法,我现在改为:
CREATE TABLE public.observations (
id integer NOT NULL,
utc_created_at timestamp with time zone NOT NULL
)
我可以进行所描述的查询吗?
给定的解决方案也可以与EXTRACT
一起使用,以按太平洋标准时间年/月分组吗?
答案 0 :(得分:0)
由于时间戳记是UTC中没有时区的时间戳记,因此您需要:
完成此操作后,您可以可靠且可复制地将其转换为所需格式的字符串。
要了解我的意思,请尝试运行:
select
utc_created_at as original_timestamp
--correct conversion to PST
, (utc_created_at at time zone'Z') at time zone 'PST' as timestamp_in_pst
, date( (utc_created_at at time zone'Z') at time zone 'PST' ) as date_from_pst
--will correctly convert it to a timestamp with timezone, but Postgres will consider your session timezone in conversions
, utc_created_at at time zone'Z' as timestamp_with_timezone_displayed_in_session_time_zone
, date(utc_created_at at time zone'Z') as date_depends_on_session
--incorrect, will interpret it as if the original timestamp is in PST
, utc_created_at at time zone'PST' as timestamp_considered_with_PST_incorrect
, date( utc_created_at at time zone 'PST') as incorrect_date
from public.observations
您知道,例如,如果它是世界标准时间1月1日的00:01,实际上应该是前一年的PST,您可以在此提琴中看到:http://sqlfiddle.com/#!17/e6d3c/10