Time Difference in Redshift

Benny picture Benny · Sep 22, 2014 · Viewed 16.9k times · Source

how to get exact time Difference between two column

eg:

   col1 date is 2014-09-21 02:00:00
   col2 date is 2014-09-22 01:00:00

output like

result: 23:00:00

I am getting result like

 Hours Minutes Seconds
 --------------------
  3    3       20
  1    2       30

using the following query

SELECT start_time,
       end_time,
       DATE_PART(H,end_time) - DATE_PART(H,start_time) AS Hours,
       DATE_PART(M,end_time) - DATE_PART(M,start_time) AS Minutes,
       DATE_PART(S,end_time) - DATE_PART(S,start_time) AS Seconds
FROM user_session

but i need like

 Difference 
 -----------
  03:03:20
  01:02:30

Answer

Joe Harris picture Joe Harris · Sep 23, 2014

Use DATEDIFF to get the seconds between the two datetimes:

DATEDIFF(second,'2014-09-23 00:00:00.000','2014-09-23 01:23:45.000')

Then use DATEADD to add the seconds to '1900-01-01 00:00:00':

DATEADD(seconds,5025,'1900-01-01 00:00:00')

Then CAST the result to a TIME data type (note that this limits you to 24 hours max):

CAST('1900-01-01 01:23:45' as TIME)