2

I need to convert the following (hh)integer column into a time column. Expected results below:

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

Can you help?

2
  • That's the 4th half hour out of the 48 half hours. Commented Jan 8, 2017 at 14:47
  • select (make_interval(mins := (hh-1)*30))::time; Commented Jan 8, 2017 at 15:40

2 Answers 2

4

You can just do:

select hh, ('00:00:00'::time + (hh - 1) * interval '30 minute') as time
from t;
Sign up to request clarification or add additional context in comments.

Comments

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'

Another solution would be to work with unix timestamps:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.