假设我有一个区间

4 days 10:00:00

在postgres。我如何将其转换为小时数(在这种情况下为106 ?)有什么活动吗,还是我应该咬紧牙关做点什么

extract(days, my_interval) * 24 + extract(hours, my_interval)

当前回答

我正在使用PostgreSQL 11,我创建了一个函数来获得2个不同时间戳之间的时间

create function analysis.calcHours(datetime1 timestamp, datetime2 timestamp)
    returns integer
    language plpgsql as $$
    declare
        diff interval;
    begin
        diff = datetime2 - datetime1;
        return (abs(extract(days from diff))*24 + abs(extract(hours from diff)))::integer;
    end; $$;

其他回答

如果你想要整数,即天数:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int

如果你转换表字段:

定义字段,使其包含秒: 创建表如果不存在测试( ... 字段INTERVAL秒(0) ); 提取值。记住,如果转换为int,你可能会在间隔变大时得到一个不愉快的惊喜: EXTRACT(EPOCH FROM field)::int

我正在使用PostgreSQL 11,我创建了一个函数来获得2个不同时间戳之间的时间

create function analysis.calcHours(datetime1 timestamp, datetime2 timestamp)
    returns integer
    language plpgsql as $$
    declare
        diff interval;
    begin
        diff = datetime2 - datetime1;
        return (abs(extract(days from diff))*24 + abs(extract(hours from diff)))::integer;
    end; $$;
select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));

::int转换遵循舍入原则。 如果你想要一个不同的结果,比如四舍五入,你可以使用相应的数学函数,比如floor。

可能最简单的方法是:

SELECT EXTRACT(epoch FROM my_interval)/3600