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

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

How to get a list of hours between two timestamp?

问题

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

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

结果应该是

  1. 14
  2. 15
  3. 16
  4. 17
  5. 18
  6. 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

  1. 14
  2. 15
  3. 16
  4. 17
  5. 18
  6. 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

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

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

更新后包括分钟:

  1. SELECT
  2. extract(hour FROM a) AS hour,
  3. CASE WHEN a = '2023-02-23 14:00'::timestamp THEN
  4. extract(minute from '2023-02-23 14:38'::timestamp - a)
  5. WHEN a = '2023-02-23 19:00'::timestamp THEN
  6. extract(minute from '2023-02-23 19:32'::timestamp - a)
  7. ELSE
  8. to_char(a - lag(a) over(), 'HH')::integer * 60
  9. END AS minutes
  10. FROM
  11. generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
  12. date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour') AS t (a);
英文:

The simple solution to get the hours:

  1. SELECT
  2. extract(hour FROM a) AS hour
  3. FROM
  4. generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
  5. date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour')
  6. AS t (a);
  7. hour
  8. ------
  9. 14
  10. 15
  11. 16
  12. 17
  13. 18
  14. 19

UPDATED to include minutes.

  1. SELECT
  2. extract(hour FROM a) AS hour,
  3. CASE WHEN a = '2023-02-23 14:00'::timestamp THEN
  4. extract(minute from'2023-02-23 14:38'::timestamp - a)
  5. WHEN a = '2023-02-23 19:00'::timestamp THEN
  6. extract(minute from '2023-02-23 19:32'::timestamp - a)
  7. ELSE
  8. to_char(a - lag(a) over(), 'HH')::integer * 60
  9. END AS minutes
  10. FROM
  11. generate_series(date_trunc('hour', '2023-02-23 14:38'::timestamp),
  12. date_trunc('hour', '2023-02-23 19:32'::timestamp), '1 hour') AS t (a);
  13. hour | minutes
  14. ------+---------
  15. 14 | 38
  16. 15 | 60
  17. 16 | 60
  18. 17 | 60
  19. 18 | 60
  20. 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:

确定