rounding a timestamp to nearest x seconds

From: Andy Colson <andy(at)squeakycode(dot)net>
To: PostgreSQL <pgsql-general(at)postgresql(dot)org>
Subject: rounding a timestamp to nearest x seconds
Date: 2012-03-07 15:09:38
Message-ID: 4F577A32.60001@squeakycode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Took me a while to figure this out, thought I'd paste it here for others
to use:

create or replace function round_timestamp(timestamp, integer) returns
timestamp as $$
select date_trunc('minute', $1) + cast(round(date_part('seconds',
$1)/$2)*$2 || ' seconds' as interval);
$$ language sql immutable;

If you pass 10 to the second argument, it'll round the timestamp to the
nearest 10 seconds. Pass 5 to round to nearest 5 seconds, etc..

-Andy

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2012-03-07 15:10:31 Re: Fixing the loss of 'template1'
Previous Message Gary Chambers 2012-03-07 14:53:56 Re: Fixing the loss of 'template1'