Postgres将整数转换为时间

时间:2017-01-08 14:42:45

标签: postgresql

我需要将以下(hh)整数列转换为时间列。预期结果如下:

hh     time
1      00:00
2      00:30
3      01:00
4      01:30
...
48     23:30

你能帮忙吗?

2 个答案:

答案 0 :(得分:3)

你可以这样做:

select hh, ('00:00:00'::time + (hh - 1) * interval '30 minute') as time
from t;

答案 1 :(得分:1)

Use INTERVAL arithmetic

SELECT 
  TIME '00:00' + (1 - 1) * INTERVAL '30 minutes',
  TIME '00:00' + (2 - 1) * INTERVAL '30 minutes',
  TIME '00:00' + (3 - 1) * INTERVAL '30 minutes',
  TIME '00:00' + (4 - 1) * INTERVAL '30 minutes',
  TIME '00:00' + (5 - 1) * INTERVAL '30 minutes',
  -- ...
  TIME '00:00' + (48 - 1) * INTERVAL '30 minutes'

另一种解决方案是使用unix时间戳:

SELECT 
  (to_timestamp((1 - 1) * 30 * 60) at time zone 'UTC')::time,
  (to_timestamp((2 - 1) * 30 * 60) at time zone 'UTC')::time,
  (to_timestamp((3 - 1) * 30 * 60) at time zone 'UTC')::time,
  (to_timestamp((4 - 1) * 30 * 60) at time zone 'UTC')::time,
  (to_timestamp((5 - 1) * 30 * 60) at time zone 'UTC')::time,
  -- ...
  (to_timestamp((48 - 1) * 30 * 60) at time zone 'UTC')::time