如何从timestamptz中提取一致的年份

时间:2013-03-26 13:44:13

标签: sql postgresql timezone timestamp-with-timezone

我正在尝试使用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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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