Md Rashedul Hoque Bhuiyan
Md Rashedul Hoque Bhuiyan

Reputation: 10641

Postgres Time Difference

I am trying to retrieve time difference in minutes from a table(login_history as t1) using postgresql .

When i tried this code

((date_part('hour', timestamp '2014-04-25 09:44:21')- date_part('hour', timestamp '2014-04-25 08:32:21'))*60 +(date_part('minutes', timestamp '2014-04-25 09:44:21')- date_part('minutes', timestamp '2014-04-25 08:32:21'))) as TimeNew

It works fine. But when i tried to retrieve information from a table t1 using this code

((date_part('hour', timestamp t1.login_date)- date_part('hour', timestamp t1.logout_date))*60 +
(date_part('minutes', timestamp t1.login_date)- date_part('minutes', timestamp t1.logout_date))
) as TimeNew

It throws this error

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "t1"

Thanks

Upvotes: 13

Views: 26493

Answers (2)

reupen
reupen

Reputation: 571

I would use the interval that results from subtracting two timestamps for a much simpler expression:

select extract (epoch from (timestamp '2014-04-25 09:44:21' - timestamp '2014-04-25 08:32:21'))::integer/60

(gives 72)

or for your table:

select extract (epoch from (t1.logout_date - t1.login_date))::integer/60

If you need to cast:

select extract (epoch from (t1.logout_date::timestamp - t1.login_date::timestamp))::integer/60

or see the to_timestamp function for custom string parsing: http://www.postgresql.org/docs/9.4/static/functions-formatting.html

Upvotes: 11

Md Rashedul Hoque Bhuiyan
Md Rashedul Hoque Bhuiyan

Reputation: 10641

I needed to remove the timestamp from the query before t1 and the query works.

Upvotes: 0

Related Questions