Add time bucketing function `time_bucket(<interval>,<timestamp>)` || `date_bin(<interval>,<timestamp>)`
See original GitHub issueUse case:
Right now one can only use date_trunc()
to easily define time buckets. date_trunc()
only supports predefine time intervals like 1 minute, 1 hour, etc. . In time-series use cases it is often necessary to define different time bucket sizes like e.g. ‘5 minutes’ or ‘20 minutes’
a workaround for this is the - error prone - integer division on the timestamp e.g.
SELECT
(ts / ( 300 * 1000)) * 300 * 1000 AS "bucket",
avg(metric)
FROM data
GROUP BY bucket
ORDER BY bucket DESC LIMIT 10;
Feature description
Have the ability to pass other time bucket sizes / intervals to date_trunc()
, e.g. date_trunc('5 minutes',ts)
or have a separate time_bucket(INTERVAL,TIMESTAMP)
function that takes an interval e.g. '5 minutes'
and a timestamp as input and returns the corresponding bucket (i.e. a timestamp that has the starting value of the bucket)
SELECT
time_bucket('5 minutes', ts) AS "bucket",
avg(metric)
FROM data
GROUP BY bucket
ORDER BY bucket DESC LIMIT 10;
Timescale time_bucket() function TS docs GH implementation
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:8 (8 by maintainers)
Top GitHub Comments
PostgreSQL 14 will implement
date_bin(stride, source, origin)
which is quite similar to the above mentionedtime_bucket()
definition. To improve compatibility with Postgres Wire Protocol, I think this should be the preferred solution. However theorigin
parameter should be optional, for usability reasons.This doesn’t necessarily have to do with the default origin, but I would expect
time_bucket('1 week',<timestamp>)
to return a Monday 00:00:00.000Z. I think this could be achieved by e.g. setting the default origin to2001-01-01
or any other year that starts with a Monday.To follow the new
date_bin
function, it might be good to be able to specify aorigin
.@BaurzhanSakhariev
yes