Re: rounding a timestamp to nearest x seconds

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: Andy Colson <andy(at)squeakycode(dot)net>
Cc: PostgreSQL <pgsql-general(at)postgresql(dot)org>
Subject: Re: rounding a timestamp to nearest x seconds
Date: 2012-03-08 02:11:57
Message-ID: CA+mi_8ZGnsq31txDrRvw=unTNVVjwWzqogfgfA4yKOndX4n+UQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Mar 7, 2012 at 3:09 PM, Andy Colson <andy(at)squeakycode(dot)net> wrote:
> 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..

Your function can only round the seconds: it cannot round on intervals
longer than one minute and always rounds down to the minute, creating
irregular intervals, e.g.:

=> select round_timestamp('2012-03-12 01:42:58', 13);
2012-03-12 01:42:52
=> select round_timestamp('2012-03-12 01:42:59', 13);
2012-03-12 01:43:05
=> select round_timestamp('2012-03-12 01:43:00', 13);
2012-03-12 01:43:00

You don't get discontinuities if you map the timestamp on the real
axis by extracting the epoch, play there and then go back into the
time domain:

create or replace function round_timestamp(timestamp, integer) returns
timestamp as $$
select 'epoch'::timestamp + '1 second'::interval * ($2 *
round(date_part('epoch', $1) / $2));
$$ language sql immutable;

This version can round on any interval specified in seconds (but it
would be easy to specify the step as interval: date_part('epoch',
interval) returns the interval length in seconds).

-- Daniele

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Aleksey Tsalolikhin 2012-03-08 02:27:13 Re: A 154 GB table swelled to 527 GB on the Slony slave. How to compact it?
Previous Message Aleksey Tsalolikhin 2012-03-07 22:05:42 Re: phantom long-running query (check_postgres.pl reports a long-running query, but the database logs don't show it)