Published on

Difference in Minutes Between Two Timestamps in PostgreSQL

In PostgreSQL, you can calculate the difference in minutes between two timestamps using the EXTRACT function to extract the difference in seconds and then converting it to minutes using the EPOCH function. This can be useful for various applications, such as calculating the duration of an event or measuring the time between two events.

Here's how you can calculate the difference in minutes between two timestamps in PostgreSQL:

SELECT EXTRACT(EPOCH FROM ((NOW() + interval '1 day')::TIMESTAMPZ - NOW())) / 60 AS minutes

In this example, we're calculating the difference in minutes between the current timestamp (NOW()) and the current timestamp plus one day (NOW() + interval '1 day'). We're using the EXTRACT function to extract the difference in seconds between the two timestamps and then dividing it by 60 to convert it to minutes.

You can replace the timestamps in the query with your own timestamps to calculate the difference between them. You can also use different intervals, such as hours, days, or months, to calculate the difference in other units of time.

SELECT EXTRACT(EPOCH FROM (end_date - start_date)) / 60 AS minutes

In this query, end_date and start_date are placeholders for your timestamps. Replace them with your actual timestamp columns or values to calculate the difference in minutes between them.

In conclusion, calculating the difference in minutes between two timestamps in PostgreSQL is a straightforward process using the EXTRACT and EPOCH functions. By following the examples provided in this post, you can perform this calculation in your own PostgreSQL queries and leverage it for various time-related tasks in your applications.