Get seconds of day in Postgres
extract()
the epoch
from the time component after casting to time
(effectively removing the date component):
SELECT extract(epoch FROM ts::time) AS seconds_of_day
You get the "number of seconds", including fractional seconds if there are any.
Very short and fast.
Test (with timestamps in unambiguous ISO format):
SELECT extract(epoch FROM ts::time) AS seconds_of_day
FROM (
VALUES
('2014-10-12 00:00:30'::timestamp) -- 30
, ('2014-10-12 00:01:30') -- 90
, ('2014-10-12 00:02:00') -- 120
, ('2014-10-12 12:00:00') -- 43200
, ('1999-12-23 23:59:59') -- 86399
, ('1999-12-23 23:59:59.123456') -- 86399.123456
) t(ts);
db<>fiddle here
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