Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL get time difference between timestamps

I've looked at many SO questions related to this but I can't seem to get anything to work. I'm not very good with semi complex SQL queries.

I want to get the difference between the current time and a column that is in unix timestamp in hours.

I'm not sure what I'm doing wrong or right for that matter. The goal is to only pull the rows that is less than 24 hours old. If there is a better way or example that works that would be great.

I tried several answers from here Timestamp Difference In Hours for PostgreSQL

I can't get this query to work no matter how many different ways I try it. wc.posted is a bigint store as unix timestamp

SELECT w.wal_id, wc.com_id, w.posted AS post_time, wc.posted AS com_time 
FROM wall as w LEFT JOIN wall_comments as wc ON w.wal_id=wc.wal_id 
WHERE (EXTRACT(EPOCH FROM wc.posted)) > current_timestamp - interval '24 hours'

Then the Error:

ERROR:  function pg_catalog.date_part(unknown, bigint) does not exist
LINE 1: ... wall_comments as wc ON w.wal_id=wc.wal_id WHERE (EXTRACT(EP...
                                                             ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

********** Error **********

ERROR: function pg_catalog.date_part(unknown, bigint) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 148

Here is a simplified fiddle

like image 882
Panama Jack Avatar asked Apr 09 '26 18:04

Panama Jack


2 Answers

From the fine manual:

A single-argument to_timestamp function is also available; it accepts a double precision argument and converts from Unix epoch (seconds since 1970-01-01 00:00:00+00) to timestamp with time zone. (Integer Unix epochs are implicitly cast to double precision.)

So to convert your bigint seconds-since-epoch to a timestampz:

to_timestamp(wc.posted)

Perhaps you're looking for this:

WHERE to_timestamp(wc.posted) > current_timestamp - interval '24 hours'
like image 177
mu is too short Avatar answered Apr 11 '26 10:04

mu is too short


Try:

SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamo_A))
FROM TableA

Details here: EXTRACT.

like image 33
Vignesh Kumar A Avatar answered Apr 11 '26 10:04

Vignesh Kumar A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!