获取两个时间戳之间的小时列表如何?

huangapple go评论57阅读模式
英文:

How to get a list of hours between two timestamp?

问题

我想要获取两个时间戳之间的所有小时。

例如,从2023-02-23 14:38到2023-02-23 19:32

结果应该是

14
15
16
17
18
19

最好我还能在计算的小时中获取分钟

小时 分钟
14 38
15 60
16 60
17 60
18 60
19 32

在PostgreSQL中是否有此查询的函数?

英文:

I want to get all hours between two timestamps.

For example from 2023-02-23 14:38 to 2023-02-23 19:32

The result should be

14 
15
16
17
18
19

better i get also additional the minutes in the calculated hour

Hour Minutes
14 38
15 60
16 60
17 60
18 60
19 32

Is there a function in postgresql for this query ?

答案1

得分: 1

获取小时的简单解决方案:

SELECT
    extract(hour FROM a) AS hour
FROM
    generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
                    date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour') 
AS t (a);

更新后包括分钟:

SELECT
    extract(hour FROM a) AS hour,
    CASE WHEN a = '2023-02-23 14:00'::timestamp THEN
        extract(minute from '2023-02-23 14:38'::timestamp - a)
    WHEN a = '2023-02-23 19:00'::timestamp THEN
        extract(minute from '2023-02-23 19:32'::timestamp - a)
    ELSE
        to_char(a - lag(a) over(), 'HH')::integer * 60
    END AS minutes
FROM
    generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
    date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour') AS t (a);
英文:

The simple solution to get the hours:


SELECT
    extract(hour FROM a) AS hour
FROM
    generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
                    date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour') 
AS t (a);

hour 
------
   14
   15
   16
   17
   18
   19

UPDATED to include minutes.

SELECT
    extract(hour FROM a) AS hour,
    CASE WHEN a = '2023-02-23 14:00'::timestamp THEN
        extract(minute from'2023-02-23 14:38'::timestamp - a)
    WHEN a = '2023-02-23 19:00'::timestamp THEN
        extract(minute from '2023-02-23 19:32'::timestamp - a)
    ELSE
        to_char(a - lag(a) over(), 'HH')::integer * 60
    END AS minutes
FROM
    generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
    date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour') AS t (a);

hour | minutes 
------+---------
   14 |      38
   15 |      60
   16 |      60
   17 |      60
   18 |      60
   19 |      32

huangapple
  • 本文由 发表于 2023年2月23日 21:42:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定