从 Postgres 中的时间戳列中提取纪元

问题描述 投票:0回答:2

从带有时区的时间戳列获取纪元的语法是什么。

我可以按以下方式使用

with time zone
,它会按预期工作

select extract(epoch from timestamp with time zone '1970-01-01 00:00:00.000 +00') ;

回归

0

select extract(epoch from timestamp with time zone '1970-01-01 00:00:00.000 -0500') ;

回归

18000.000000

太棒了!

但这会返回相同的纪元:

select extract(epoch from ts ) 
from(
    select to_timestamp(ts, 'yyyy-mm-dd h24:mi:ss') ts
    from (
        select unnest (array[
        '1970-01-01 00:00:00.000 +00',
        '1970-01-01 00:00:00.000 -0500'
        ]) ts
    )
);
18000.000000
18000.000000

当我提取一列时间戳的纪元时,我应该将

with time zone
放在哪里?

我尝试了以下方法但没有成功:

  • epoch from ts with time zone
    --失败 SQL 错误 [42601]:错误:“with”处或附近的语法错误
  • epoch from ts::timestamp with time zone
    - 运行,但为两者提供相同的值
sql postgresql
2个回答
0
投票

这可能就是您正在寻找的

select extract(epoch from ts) 
from(
  select ts::TIMESTAMPTZ at time zone 'UTC' ts
   from (
       select unnest (array[
       '1970-01-01 00:00:00.000+00',
       '1970-01-01 00:00:00.000-0500'
       ]) ts
   ) a
) b;

根据您的查询;在使用纪元之前,需要先通过强制转换来识别时区。


0
投票

在 PostgreSQL 中,当您将文本时间戳转换为带时区的时间戳时,转换将使用当前时区设置,除非您在转换中明确指定时区。

但是,由于您的时间戳已经包含时区信息,因此您可以直接将它们转换为

timestamptz
,而无需使用
to_timestamp

SELECT extract(epoch FROM ts::timestamptz) 
FROM (
    SELECT unnest(ARRAY[
        '1970-01-01 00:00:00.000 +00',
        '1970-01-01 00:00:00.000 -0500'
    ]) AS ts
) subquery;

这将正确解释时间戳中包含的时区信息并提供正确的纪元值。

0.000000
18000.000000


© www.soinside.com 2019 - 2024. All rights reserved.