[英]How to convert timestamp without timezone and integer representing timezone to a new timestamp without timezone in PostgreSQL
Let's say I have a table with two fields: snapshot_date (timestamp without timezone) and timezone (integer),假设我有一个包含两个字段的表:snapshot_date(没有时区的时间戳)和时区(整数),
snapshot_date![]() |
timezone![]() |
---|---|
2021-01-12 08:00:00 ![]() |
-3 ![]() |
2021-01-12 00:00:00 ![]() |
-5 ![]() |
I need to extract the local hour from this table, I tried with (EXTRACT (hour from timestamp))::integer + timezone
, this would work for the first row, giving an hour result of 5
but with the second row you get -5
, which should actually be 19
since the corresponding date adjusted with timezone is 2021-01-11 19:00:00
.我需要从该表中提取本地时间,我尝试使用
(EXTRACT (hour from timestamp))::integer + timezone
,这适用于第一行,给出5
的小时结果,但第二行你得到-5
,实际上应该是19
,因为用时区调整的相应日期是2021-01-11 19:00:00
。 So what I want to do is calculate a new snapshot_date adjusted with the timezone, so I can correctly extract the hour after.所以我想做的是计算一个用时区调整的新快照日期,这样我就可以正确提取一小时后的时间。
You need to first add the number of hours to the timestamp, then extract the hour:您需要先将小时数添加到时间戳中,然后提取小时数:
extract(hour from snapshot_date + make_interval(hours => timezone))
Something like:就像是:
show timezone; US/Pacific
select ('2021-01-12 08:00:00'::timestamp::text || (-3)::text)::timestamptz;
2021-01-12 03:00:00-08
select extract(hour from('2021-01-12 08:00:00'::timestamp::text || (-3)::text)::timestamptz);
3
Managed to get the expected result with:设法通过以下方式获得预期结果:
extract(hour from timestamp + interval '1 hour' * timezone)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.