与currenttimestamp.com和timestamp.1e5b.de比较时,我没有从Postgresql获得预期的时间:
这将返回正确的时间戳:
SELECT extract(epoch from now());
虽然这不是:
SELECT extract(epoch from now() at time zone 'utc');
我住在时区UTC 02.从Postgresql获取当前unix时间戳的正确方法是什么?
这将返回正确的时间和时区:
SELECT now(); now ------------------------------- 2011-05-18 10:34:10.820464+02
另一个比较:
select now(),extract(epoch from now()),extract(epoch from now() at time zone 'utc'); now | date_part | date_part -------------------------------+------------------+------------------ 2011-05-18 10:38:16.439332+02 | 1305707896.43933 | 1305700696.43933 (1 row) Unix timestamp from the web sites: 1305707967
从像now()这样的postgres timestamptz获取Unix时间戳很简单,就像你说的那样:
select extract(epoch from now());
关于从timestamptz类型获取绝对时间,包括now(),这真的是你需要知道的.
当你有一个时间戳字段时,事情变得复杂.
当您将timestamptz数据(例如now())放入该字段时,它将首先转换为特定时区(在时区显式或转换为会话时区),并丢弃时区信息.它不再是指绝对时间.这就是为什么你通常不希望将时间戳存储为时间戳,并且通常会使用timestamptz – 也许电影会在每个时区的特定日期下午6点发布,这就是用例.
如果您只在一个时区工作,那么您可能会使用时间戳(错误).转换回timestamptz非常聪明,可以应对DST,并且为了转换目的,假设时间戳位于当前时区.以下是GMT / BST的示例:
select '2011-03-27 00:59:00.0+00'::timestamptz::timestamp::timestamptz,'2011-03-27 01:00:00.0+00'::timestamptz::timestamp::timestamptz; /* |timestamptz |timestamptz | |:---------------------|:---------------------| |2011-03-27 00:59:00+00|2011-03-27 02:00:00+01| */
但是,请注意以下令人困惑的行为:
set timezone to 0; values(1,'1970-01-01 00:00:00+00'::timestamp::timestamptz),(2,'1970-01-01 00:00:00+02'::timestamp::timestamptz); /* |column1|column2 | |------:|:---------------------| | 1|1970-01-01 00:00:00+00| | 2|1970-01-01 00:00:00+00| */
Postgresql never examines the content of a literal string before determining its type,and therefore will treat both […] as timestamp without time zone. To ensure that a literal is treated as timestamp with time zone,give it the correct explicit type…In a literal that has been determined to be timestamp without time zone,Postgresql will silently ignore any time zone indication