time_bucket()
Note that daylight savings time boundaries means that the amount of data aggregated into a bucket after such a cast can be irregular. For example, if the bucket_width
is 2 hours, the number of UTC hours bucketed by local time on daylight savings time boundaries can be either three hours or one hour.
If you use months as an interval for bucket_width
, you cannot combine it with a non-month component. For example, 1 month
and 3 months
are both valid bucket widths, but 1 month 1 day
and 3 months 2 weeks
are not.
To report the middle of the bucket, instead of the left edge:
SELECT time_bucket('5 minutes', time) + '2.5 minutes'
AS five_min, avg(cpu)
FROM metrics
GROUP BY five_min
ORDER BY five_min DESC LIMIT 10;
For rounding, move the alignment so that the middle of the bucket is at the five minute mark, and report the middle of the bucket:
To shift the alignment of the buckets you can use the origin parameter passed as a timestamp, timestamptz, or date type. This example shifts the start of the week to a Sunday, instead of the default of Monday:
SELECT time_bucket('1 week', timetz, TIMESTAMPTZ '2017-12-31')
AS one_week, avg(cpu)
FROM metrics
GROUP BY one_week
WHERE time > TIMESTAMPTZ '2017-12-01' AND time < TIMESTAMPTZ '2018-01-03'
ORDER BY one_week DESC LIMIT 10;
The value of the origin parameter in this example is 2017-12-31
, a Sunday within the period being analyzed. However, the origin provided to the function can be before, during, or after the data being analyzed. All buckets are calculated relative to this origin. So, in this example, any Sunday could have been used. Note that because time < TIMESTAMPTZ '2018-01-03'
is used in this example, the last bucket would have only 4 days of data. This cast to TIMESTAMP converts the time to local time according to the server’s timezone setting.
SELECT time_bucket('1 month', ts, 'Europe/Berlin') AS month_bucket,
avg(temperature) AS avg_temp
FROM weather
GROUP BY month_bucket
ORDER BY month_bucket DESC LIMIT 10;