tags:

views:

44

answers:

2

I'm trying to extract the time of day from a 'timestamp' column in PostgreSQL. Here is how I did it but... it's awful. An idea of how to do it better ?

SELECT (
    date_part('hour', date_demande)::text   || ' hours '   ||
    date_part('minute', date_demande)::text || ' minutes ' ||
    date_part('second', date_demande)::text || ' seconds'
    )::interval AS time_of_day

FROM table;
+4  A: 

It depends in which format you want it ofcourse.

But instead of using date_part it might be easier to use to_char instead. http://www.postgresql.org/docs/8.4/interactive/functions-formatting.html#FUNCTIONS-FORMATTING-DATETIME-TABLE

So in your case perhaps something like this:

to_char(current_timestamp, 'HH:MI:SS')
WoLpH
To get closer to the asked result: `to_char(current_timestamp, 'HH "hours" MI "minutes" SS "seconds"')`
DrColossos
this answer does not do the same thing I wanted to do : i don't want to get a "text" answer but a "time" answer (I'm talking about the type of the result). The correct answer was the one i checked. Thank you anyway
Ghislain Leveque
@Ghislain Leveque: ah, I misunderstood. An alternative solution in that case is `SELECT colname::time`
WoLpH
+4  A: 

If you need the exact time from a timestamp, just cast to time:

SELECT
    CAST(colname AS time)
FROM
    tablename;

If you need formatting, to_char() is your best option.

Frank Heikens
This is the only correct answer, I wanted the time typed as a time and not as a text
Ghislain Leveque