为什么在时区工作不如预期?

Why is at time zone works not as was expected?

我有一个服务器可以给我一些按天分组的信息,所以我尝试使用 date_trunc(),但由于时区,我知道我的数据库中的 2020-06-05 21:00:00 实际上是 [=14] =].

所以如果我只使用 date_trunc,我得到 2020-06-05 00:00:00,但我需要 2020-06-06 00:00:00

我正在尝试这个:

  select tm ,  date_trunc('day', (tm) at time zone '+3')
   from scm.tbl
  where (tm BETWEEN '2020-06-05 15:00:00+00:00:00' AND '2020-06-08 20:59:00+00:00:00')
  order by tm

我有这个:

2020-06-05 17:59:59  | 2020-06-05 00:00:00
2020-06-05 18:00:10  | 2020-06-06 00:00:00

在 18:00 日期变成了 2020-06-06,但它不应该。为什么呢?我在这里做错了什么?

问题是 AT TIME ZONE 会将 timestamp without time zone 转换为 timestamp with time zone,并且会根据您当前的 timezone 设置再次处理。

因此您需要使用 AT TIME ZONE 两次,首先是在正确的时区中解释时间戳,然后提取 UTC 时钟在该时间显示的内容:

SELECT tm, date_trunc('day', tm AT TIME ZONE '+3' AT TIME ZONE 'UTC')
FROM scm.tbl
WHERE (tm BETWEEN '2020-06-05 15:00:00+00:00:00' AND '2020-06-08 20:59:00+00:00:00')
ORDER BY tm;

我在这里找到了答案timezone aware date_trunc function

当我在回答中看到这个时:

    timestamp with time zone '2001-01-1 00:00:00+0100' at time zone '-02'

因为tm是+03:00:00,我又加了...

所以我能做的是:

   date_trunc('day', tm at time zone '0')

我想一定有更好的方法来做到这一点,不用'0'