是否有postgresql函数会将时间戳舍入到最接近的分钟?输入值是时间戳,返回值应该是时间戳。
答案 0 :(得分:94)
使用内置函数date_trunc(text, timestamp)
,例如:
select date_trunc('minute', now())
修改:这会截断到最近的分钟。要获得舍入的结果,请先为时间戳添加30秒,例如:
select date_trunc('minute', now() + interval '30 second')
这将返回最近的分钟。
答案 1 :(得分:13)
回答类似(更通用)的问题,
“......到最近的分钟间隔”(1分钟,5分钟,10分钟等)
CREATE FUNCTION round_minutes(TIMESTAMP WITHOUT TIME ZONE, integer)
RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$
SELECT
date_trunc('hour', $1)
+ cast(($2::varchar||' min') as interval)
* round(
(date_part('minute',$1)::float + date_part('second',$1)/ 60.)::float
/ $2::float
)
$$ LANGUAGE SQL IMMUTABLE;
CREATE FUNCTION round_minutes(TIMESTAMP WITHOUT TIME ZONE, integer,text)
RETURNS text AS $$
SELECT to_char(round_minutes($1,$2),$3)
$$ LANGUAGE SQL IMMUTABLE;
SELECT round_minutes('2010-09-17 16:23:12', 5);
-- 2010-09-17 16:25:00
SELECT round_minutes('2010-09-17 16:23:12', 10, 'HH24:MI');
-- 16:20
改编自http://wiki.postgresql.org/wiki/Round_time并改编为@CrowMagnumb显示的“精确回合”。
答案 2 :(得分:5)
在尝试使用Peter的上述答案来创建天花板和地板功能时,我发现在调用舍入功能时你也必须考虑秒数。这是我的一组函数,它们将是round,floor和ceiling时间戳。
CREATE OR REPLACE FUNCTION round_minutes( TIMESTAMP WITHOUT TIME ZONE, integer)
RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$
SELECT date_trunc('hour', $1) + (cast(($2::varchar||' min') as interval) * round( (date_part('minute',$1)::float + date_part('second',$1)/ 60.)::float / cast($2 as float)))
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION floor_minutes( TIMESTAMP WITHOUT TIME ZONE, integer )
RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$
SELECT round_minutes( $1 - cast((($2/2)::varchar ||' min') as interval ), $2 );
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION ceiling_minutes( TIMESTAMP WITHOUT TIME ZONE, integer )
RETURNS TIMESTAMP WITHOUT TIME ZONE AS $$
SELECT round_minutes( $1 + cast((($2/2)::varchar ||' min') as interval ), $2 );
$$ LANGUAGE SQL IMMUTABLE STRICT;
答案 3 :(得分:2)
缩小时间戳
CREATE or replace FUNCTION date_round_down(base_date timestamptz, round_interval INTERVAL)
RETURNS timestamptz AS $BODY$
SELECT TO_TIMESTAMP(EXTRACT(epoch FROM date_trunc('hour', $1))::INTEGER + trunc((EXTRACT(epoch FROM $1)::INTEGER - EXTRACT(epoch FROM date_trunc('hour', $1))::INTEGER) / EXTRACT(epoch FROM $2)::INTEGER) * EXTRACT(epoch FROM $2)::INTEGER)
$BODY$ LANGUAGE SQL STABLE;
SELECT date_round_down('2017-06-02 16:39:35', '15 minutes') -- 2017-06-02 16:30:35