2

我正在尝试使用 Postgres 函数extract()timestamptz列中获取年份,但得到了意想不到的结果。我预计它将使用 UTC,但似乎使用系统的本地时区(在我的情况下为 EST)。无论时间戳或系统的时区是什么,如何获得extract返回 UTC 的函数?

示例 1:

testdb=# create table foo ( t timestamptz check( extract(year from t)::int = 2013) );

testdb=# \d foo
              Table "public.foo"
 Column |           Type           | Modifiers
--------+--------------------------+-----------
 t      | timestamp with time zone |
Check constraints:
    "foo_t_check" CHECK (date_part('year'::text, t)::integer = 2013)

testdb=# insert into foo values ('2013-01-01 01:49:05.048+00');
ERROR:  new row for relation "foo" violates check constraint "foo_t_check"
DETAIL:  Failing row contains (2012-12-31 20:49:05.048-05).

示例 2:

testdb=# SELECT EXTRACT(year FROM '01-01-1970 00:00:00 UTC+01'::timestamp with time zone);
 date_part
-----------
      1969
(1 row)
4

2 回答 2

2

利用at time zone

create table foo (
    t timestamptz
    check (extract(year from t at time zone 'UTC') = 2013)
);

select extract(year from
    '01-01-1970 00:00:00 utc+01'::timestamp with time zone at time zone 'utc'
    );
 date_part 
-----------
      1970
于 2013-03-26T14:03:54.087 回答
0

我相信这样的事情:

extract(year from t::timestamp with time zone)

工作示例:

SELECT EXTRACT(year FROM 
               '01-01-1970 00:00:00 UTC+01'::timestamp 
               with time zone)

返回1970

于 2013-03-26T13:49:39.217 回答