在 PostgreSQL 数据库中,时间的表示方法非常丰富和成熟,Unix Time 在 Pg 数据库中同样存在,那么怎样进行 Unix Time 和 Timestamp 的时间转换呢?
获取 Unix Time ,可以用如下一些方法:
enmotech=# select extract(epoch from now());
date_part
------------------
1568627888.43009
(1 row)
enmotech=# select date_part('epoch',current_timestamp)::int;
date_part
------------
1568627897
(1 row)
将这个时间转换为常规时间:
enmotech=# select timestamp 'epoch'+ 1568627897 * interval '1 second';
?column?
---------------------
2019-09-16 09:58:17
(1 row)
注意,如果不加时区,以上转换会因为时区而不同。
增加时区之后,转换就会回归正常:
enmotech=# show Timezone;
TimeZone
----------
PRC
(1 row)
enmotech=# SELECT TIMESTAMP WITH Time Zone 'epoch' + 1568627397 * interval '1 second';
?column?
------------------------
2019-09-16 17:49:57+08
(1 row)
通过 to_timestamp 函数也可以进行直接简便的转换:
enmotech=# select to_timestamp(1568627897);
to_timestamp
------------------------
2019-09-16 17:58:17+08
(1 row)