date_bin()
一个用于将时间戳转换为指定时间间隔开始的函数
date_bin() 是一个系统函数,用于将任意时间戳强制转换为最近指定时间间隔的开始。例如,出于调度目的,可能需要确定一个时间戳对应于一小时内的哪个 15 分钟间隔。
date_bin() 函数已在 PostgreSQL 14 中添加。
用法
date_bin (strideINTERVAL,sourceTIMESTAMP,originTIMESTAMP) →TIMESTAMP
date_bin (strideINTERVAL,sourceTIMESTAMP WITH TIME ZONE,originTIMESTAMP WITH TIME ZONE) →TIMESTAMP WITH TIME ZONE
变更历史
- PostgreSQL 14
- 添加(提交 49ab61f0)
在 PostgreSQL 13 及更早版本中模拟 date_bin()
在 PostgreSQL 13 及更早版本中,类似以下的函数应提供与 date_bin() 相同的功能。
CREATE OR REPLACE FUNCTION date_bin ( stride INTERVAL, source_ts TIMESTAMPTZ, base_ts TIMESTAMPTZ) RETURNS TIMESTAMPTZ LANGUAGE SQL IMMUTABLE AS $$ SELECT base_ts + FLOOR(EXTRACT(epoch FROM source_ts - base_ts) / EXTRACT(epoch FROM stride))::BIGINT * stride; $$;
示例
date_bin() 的基本用法示例
postgres=# SELECT NOW(), date_bin('10 minutes', NOW(), '2001-01-01');
now | date_bin
-------------------------------+------------------------
2021-03-25 17:25:56.817198+02 | 2021-03-25 17:20:00+02
(1 row)
这里,时间 17:25:56.817198+02 被“向下舍入”到最近的常规 10 分钟标记,即:2021-03-25 17:20:00+02。
如果作为第三个参数提供的时间戳(“原点”)晚于输入时间戳,则返回的时间戳将“向上舍入”。
postgres=# SELECT now(), date_bin('10 minutes', now(), '2999-01-01');
now | date_bin
-------------------------------+------------------------
2021-03-25 18:30:16.082261+02 | 2021-03-25 18:40:00+02
(1 row)
如果其中包含特定时间,则该时间将用作返回时间戳的偏移量,例如:
postgres=# SELECT now(), date_bin('10 minutes', now(), '1999-01-01 00:05:00');
now | date_bin
------------------------------+------------------------
2021-03-25 18:32:09.61745+02 | 2021-03-25 18:25:00+02
(1 row)
无法将月份或年份用作间隔
postgres=# SELECT date_bin('10 years', '2021-01-01', '2001-01-01');
ERROR: timestamps cannot be binned into intervals containing months or years
参考资料
- PostgreSQL documentation: date_bin
有用链接
- PostgreSQL: mapping timestamps (date_bin) - 2022 年 4 月 Hans-Jürgen Schönig / CyberTec 的博客文章
- Waiting for PostgreSQL 14 - Add date_bin function - 2021 年 3 月 depesz 的博客文章
另请参阅
反馈
请在此处 提交关于“date_bin()”的任何评论、建议或更正。