SoFunction
Updated on 2025-04-08

postgresql obtains two time types hour difference cases

I won't say much nonsense, read the code~

select extract(day from t) * 24 + extract(hour from t) from (select (timestamp '2013-12-14 12:00:00' - timestamp '2013-12-11 4:00:00') as t) as a;

For example, there are two fields in table a, starting and end

select extract(day from (end-start)) * 24 + extract(hour from (end-start)) from a

Supplement: PostgreSQL obtains the difference in seconds between two timestamps

sql statement

SELECT EXTRACT(EPOCH FROM (TIMESTAMP '2017-12-16 12:21:13'- TIMESTAMP '2017-12-15 12:21:00'));

86413

Calculate the difference between two times and update another time field

UPDATE your_table

SET this_time=(EXTRACT(EPOCH FROM (time_a-time_b)));

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.