PostgreSQL – Get Seconds of Day

datetimepostgresql

In Java we use Joda-Time to get the seconds of a day as an int value (despite the date):

date: 10-10-2014 00:00:30 -> second 30 of day
date: 11-10-2014 00:01:30 -> second 90 of day
date: 12-10-2014 00:02:00 -> second 120 of day

Is there a way to do the same in PostgresSQL?

Best Answer

Use the extract() method:

select extract(second from current_timestamp) +
       extract(minute from current_timestamp) * 60 +
       extract(hour from current_timestamp) * 60 * 60;

of course this can be put into a function:

create or replace function total_seconds(p_timestamp timestamp)
 returns int
as
$$
  select (extract(second from p_timestamp) +
         extract(minute from p_timestamp) * 60 +
         extract(hour from p_timestamp) * 60 * 60)::int;
$$
language sql;

more details are in the manual:
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT