当结束时间有时超过午夜时,如何在 postgresql 中计算两次之间的持续时间
How to compute duration between two times in postgresql when the end time is sometimes past midnight
我必须根据 start_time 和 end_time 计算 postgres 中事件的持续时间,两者都是 HH:MM:SS 格式。只需 end_time - start_time 即可:
create table test_date as
select sum(eindtijd - starttijd) as tijdsduur
from evenementen_2019;
这会导致 HH:MM:SS 格式的间隔。但有时 end_time 是第二天。示例:
start_time end_time duration computed
18:00 21:00 3:00 3:00
18:00 0:00 6:00 -18:00
18:00 1:00 7:00 -17:00
我只有时间没有时区,没有日期。
解决方案在概念上很简单:当持续时间 < 0 时,加上 24 小时。所以我尝试了:
update test_date
set duration = to_date('24:00:00', 'HHMMSS') - duration
where duration < 0 * interval '1' second;
这会产生一个错误:
ERROR: column "duration" is of type interval but expression is of type timestamp without time zone
没错,我认为 timestamp - interval
会产生时间戳。我不知道如何解决这个问题。有人知道解决这个问题的最好方法是什么吗?
I thought that a timestamp - interval yields a timestamp
确实如此。然后您尝试将生成的时间戳存储到类型为 interval 的列中,但这是行不通的。
请注意,如果它在这部分幸存下来,它仍然无法正常工作,因为您的 to_date
函数调用将在 运行 时失败。
你说你应该加上 24 小时,但你试图做的是从 24 小时中减去(错误类型),如果它确实有效,那将是错误的。
您可以将您所说的几乎逐字翻译成 SQL:
update test_date
set duration = duration + interval '24 hours'
where duration < 0 * interval '1' second;
我必须根据 start_time 和 end_time 计算 postgres 中事件的持续时间,两者都是 HH:MM:SS 格式。只需 end_time - start_time 即可:
create table test_date as
select sum(eindtijd - starttijd) as tijdsduur
from evenementen_2019;
这会导致 HH:MM:SS 格式的间隔。但有时 end_time 是第二天。示例:
start_time end_time duration computed
18:00 21:00 3:00 3:00
18:00 0:00 6:00 -18:00
18:00 1:00 7:00 -17:00
我只有时间没有时区,没有日期。
解决方案在概念上很简单:当持续时间 < 0 时,加上 24 小时。所以我尝试了:
update test_date
set duration = to_date('24:00:00', 'HHMMSS') - duration
where duration < 0 * interval '1' second;
这会产生一个错误:
ERROR: column "duration" is of type interval but expression is of type timestamp without time zone
没错,我认为 timestamp - interval
会产生时间戳。我不知道如何解决这个问题。有人知道解决这个问题的最好方法是什么吗?
I thought that a timestamp - interval yields a timestamp
确实如此。然后您尝试将生成的时间戳存储到类型为 interval 的列中,但这是行不通的。
请注意,如果它在这部分幸存下来,它仍然无法正常工作,因为您的 to_date
函数调用将在 运行 时失败。
你说你应该加上 24 小时,但你试图做的是从 24 小时中减去(错误类型),如果它确实有效,那将是错误的。
您可以将您所说的几乎逐字翻译成 SQL:
update test_date
set duration = duration + interval '24 hours'
where duration < 0 * interval '1' second;