Reputation: 13
I have two fields dateTS
and closingTime
.
dateTS
is a normal timestamp field (e.g. 2019-07-13 22:31:10.000000)closingTime
is a HH:MM format of when a store closes (e.g. 23:00)I need a PostgreSQL query to subtract the two field and get the number of minutes difference between them.
Using the examples given above the difference between the two fields would be 28 minutes
So far I've tried different variations of the datediff function, but it won't work.
My guess is I either have to
closingTime
which is the same day as the dateTs
field and subtract the 2 timestamps.or
Upvotes: 0
Views: 3307
Reputation: 174
Cast your closing time to an interval and the timestamp to time and then subtract the two. By casting the timestamp to time you are effectively discarding the date part. You can the subtract one from the other to generate the difference as an interval.
select closingTime::interval - dateTS::time...
e.g.:
# select '23:00'::interval - now()::time;
?column?
-----------------
05:31:00.031141
(1 row)
If needed you can then convert the interval to minutes:
# select extract(epoch from ('23:00'::interval - now()::time)) / 60;
?column?
------------------
327.435313083333
(1 row)
Upvotes: 0
Reputation:
You can just subtract them by converting the timestamp to a time:
select closingtime - datets::time
from your_table;
That will give you an interval as the result.
To convert that to minutes you can get the number of seconds and divide it by 60:
select (extract epoch from closingtime - datets::time) / 60
from your_table;
Upvotes: 1