13

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

1
  • 1
    Your calculation is wrong. Change the second timestamp to '2014-04-24 08:32:21' and the problem will be obvious. Calculate the interval first, then take the result apart to express it in minutes. Commented Sep 13, 2015 at 10:38

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.