Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to extract the time of day?

Tags:

sql

postgresql

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;
like image 379
Ghislain Leveque Avatar asked Sep 16 '10 07:09

Ghislain Leveque


1 Answers

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.

like image 151
Frank Heikens Avatar answered Oct 28 '22 02:10

Frank Heikens