How I can round to nearest X minutes?
Here\'s my attempt:
DECLARE
_stamp ALIAS FOR $1; -- timestamp
_nearest ALIAS FOR $2; -- minutes (integer)
Further to my previous answer, here's a function that puts it all together and does exactly what you ask for:
CREATE FUNCTION date_round(base_date timestamptz, round_interval interval)
RETURNS timestamptz AS $BODY$
SELECT '1970-01-01'::timestamptz
+ (EXTRACT(epoch FROM $1)::integer + EXTRACT(epoch FROM $2)::integer / 2)
/ EXTRACT(epoch FROM $2)::integer
* EXTRACT(epoch FROM $2)::integer * interval '1 second';
$BODY$ LANGUAGE SQL STABLE;
And here's an example of calling it:
SELECT date_round(now(), '15 minutes');
You can supply any interval you want and it should work. As coded it rounds to the nearest interval, either up or down.
If you wanted to truncate instead then just remove the + EXTRACT(epoch FROM $2)::integer / 2)
.
Hopefully this will now act as a definitive answer that accepts the correct argument types (interval rather than integer number of minutes).