n1 avatar

Postgres and date subtracting

n1-cz

Published: 13 Dec 2018 › Updated: 13 Dec 2018Postgres and date subtracting

Postgres and date subtracting

Imagine you have a table with two date(time) columns. Typicaly start and end. Let’s say it’s a table with opening hours of shops in your city. How do you select number of hours that a shop is open for?

Interval

Postgres has quite nifty data type called interval. However the output is relative to it’s length. It might be 1 dayor 2 weeks. For our purpose we do need the interval in fixed format  - in hours. This can be done with a bit of math. So the solution might be:

SELECT EXTRACT(epoch FROM (NOW() + interval '1 week' - NOW())) / 3600;

This snippet returns 168 because 168 hours is one week. For our case we can use sometghing like:

SELECT
    EXTRACT(epoch FROM ("end" - "start")) / 3600
FROM
    ...
;

Hope it will help you one day.

Leave Postgres and date subtracting to:

Written by

Python dev, tomorrow tech guy.

Read more #postgres posts


Best Posts From n1

We have not curated any of n1-cz's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From n1