PostgreSQL自动时区转换为本地

时间:2017-09-28 20:37:03

标签: sql postgresql timezone

我正在努力寻找能够根据timezone子句中的输入参数动态转换Where的查询。它应该能够根据WITH中的键和值确定适当的时区转换。系统时区位于 UTC 中。

我有大约8个时区可以使用并寻找更智能的方法来检测转换,而无需始终更改At Time Zone 'pst'

这是我到目前为止,但语法需要一些帮助:

with
    data(id, timezone) AS (values
      (2, 'US/Pacific'),
      (5, 'US/Mountain'),
      (10, 'US/Eastern'))

select data.id, marg.timestamp, marg.value, structure.market 
from data, marg, structure 
where id in (2,5,10)
and marg.timestamp between '2017-01-01' and '2017-01-31'

此外,如果有更好的方法来实现这一点,我会接受反馈。

理想情况下,输出看起来像这样:

utc                 |id| timezone   | local_time            | value
--------------------+--+------------+---------------------- +----------------
2017-01-01 22:19:36 |2 | US/Pacific | 2017-01-01 15:19:36   | 2435
2017-01-10 22:29:36 |2 | US/Pacific | 2017-01-10 15:29:36   | 215
2017-01-30 22:39:36 |2 | US/Pacific | 2017-01-30 15:29:36   | 2150
2017-01-28 22:19:36 |5 | US/Mountain| 2017-01-28 16:19:36   | 11341
2017-01-29 22:19:36 |5 | US/Mountain| 2017-01-29 16:19:36   | 131
2017-01-04 22:19:36 |10| US/Mountain| 2017-01-04 16:19:36   | 134
2017-01-05 22:19:36 |10| US/Eastern | 2017-01-05 18:19:36   | 2451

它以UTC为系统时间并转换为适当的时区local_time

1 个答案:

答案 0 :(得分:0)

不确定如果我理解正确,您是否想在某些列表中使用时区转换为?那么,就像这里:

t=# with
    data(id, timezone) AS (values
      (2, 'US/Pacific'),
      (5, 'US/Mountain'),
      (10, 'US/Eastern'))
select *, now at time zone timezone ajusted from now()
join data on true;
              now              | id |  timezone   |          ajusted
-------------------------------+----+-------------+----------------------------
 2017-09-28 22:13:27.904796+01 |  2 | US/Pacific  | 2017-09-28 14:13:27.904796
 2017-09-28 22:13:27.904796+01 |  5 | US/Mountain | 2017-09-28 15:13:27.904796
 2017-09-28 22:13:27.904796+01 | 10 | US/Eastern  | 2017-09-28 17:13:27.904796
(3 rows)