PostgreSQL - How to calculate difference between two timestamps?

You have two timestamp values: timestamp1 and timestamp2 and want to find the difference between the two.

If you want the results in years, months, days, hours, etc:

SELECT age(timestamp1, timestamp2);

If you want the results in seconds only:

SELECT EXTRACT(EPOCH FROM timestamp 'timestamp1') -
       EXTRACT(EPOCH FROM timestamp 'timestamp2');

Or casting it this way:

SELECT
    EXTRACT(EPOCH FROM ('timestamp1'::timestamp - 'timestamp2'::timestamp));

Example:

SELECT
    EXTRACT(EPOCH FROM ('2018-06-28 12:01:38'::timestamp - '2017-12-11 11:30'::timestamp));
Find difference between two timestamps

*Need a good GUI Tool for PostgreSQL? TablePlus is a modern, native tool with an elegant UI that allows you to simultaneously manage multiple databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server and more.
*

Download TablePlus free.

TablePlus GUI Tool PostgreSQL

← All posts