How I can round to nearest X minutes?
Here\'s my attempt:
DECLARE
_stamp ALIAS FOR $1; -- timestamp
_nearest ALIAS FOR $2; -- minutes (integer)
You can do it as a simple SQL statement, substitute CURRENT_TIMESTAMP with your TIMESTAMP value.
SELECT date_trunc('minute', CURRENT_TIMESTAMP::timestamp without time zone)
+ (
CASE WHEN extract(second from CURRENT_TIMESTAMP ) >= 30
THEN 1::text
ELSE 0::text
END
|| ' minute'
)::interval ;
An optimization, would be adding 30 seconds and then just doing date_trunc()
, I knew this before but special thanks irc://irc.freenode.net/#postgresql
's StuckMojo
SELECT date_trunc(
'minute'
, CURRENT_TIMESTAMP::timestamp without time zone
+ '30 seconds'::interval
);
update @stephen, sure it does -- even though technically speaking that isn't what the question called for.
CREATE OR REPLACE FUNCTION round_trunc ( in text, in timestamp ) RETURNS timestamp without time zone AS $$
SELECT pg_catalog.date_trunc(
$1
, $2::timestamp without time zone
+ ('0.5 ' || $1 )::interval
)
$$ LANGUAGE sql VOLATILE;
Oh wait, I see what he is asking for, he wants to round to the nearest abstract sub-unit of time. Like a quarter hour, I'm way off here.