42

I'm new to PostgreSQL (I have been using MS SQL for many years) and need to convert a numeric column which contains a time in seconds to HH:MM:SS format.

I have Googled and found that to_char(interval '1000s', 'HH24:MI:SS') works so I am attempting to use this with my field name:

to_char(fieldname, 'HH24:MI:SS') gives an error cannot use "S" and "PL"/"MI"/"SG"/"PR" together

to_char(fieldname::interval, 'HH24:MI:SS') gives an error cannot cast type numeric to interval

Can anyone show me where I am going wrong?

4
  • fieldname is an integer ? further, what output do you expect if you have an interval bigger than one day ? Commented May 25, 2010 at 14:49
  • 1
    @leonbloy: HH24 can go beyond 24, despite its name. Commented May 25, 2010 at 14:55
  • @Quassnoi: Correct. Just wondered if that's what the poster wanted. Commented May 25, 2010 at 15:42
  • @leonbloy: yes, it is a numeric(18,0). It is possible for it to be > 24 hours but highly unlikely - it's JIRA work logs I'm looking at Commented May 27, 2010 at 8:51

2 Answers 2

69
SELECT TO_CHAR('1000 second'::interval, 'HH24:MI:SS') 

or, in your case

SELECT TO_CHAR((mycolumn || ' second')::interval, 'HH24:MI:SS') FROM mytable 
Sign up to request clarification or add additional context in comments.

7 Comments

or mycolumn * '1 second'::interval which will avoid reparsing the textual format over and over (although it doesn't make much practical difference in this case)
@Quassnoi is it possible if i will get 1:20:30s then convert into 80:30 please help me
@AnkitDoshi: please post it as another question.
The OP didn't ask but if you came here trying to make the same transformation using Redshift, this will work because isn't actually supported.
For some reason this didn't work for me until I explicitly used a concat() on mycolumn and second ... but then perfect so thank you.
|
42

To convert seconds to HH:MM:SS

SELECT 120 * interval '1 sec'; 

You will get 00:02:00

To convert minutes to HH:MM:SS

SELECT 120 * interval '1 min'; 

You will get 02:00:00

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.