2017-07-21 120 views
-1

我試圖做這樣的事情來計算入口/出口時間差:兩個SimpleDateFormat的日期差異SQL

SELECT entry_time - exit_time AS dwell

然而,認爲值是SimpleDateFormat的:

2017-07-15T13:00:37-05:00 

因此,我很難找出CAST或CONVERT它們在Postgre SQL中的問題

我是一個可以在PySpark中做到這一點,但現在我只需要使用標準SQL來完成此操作。這裏是一個在Spark中工作的例子:

import pyspark.sql.functions as F 
timeFmt = "yyyy-MM-dd'T'HH:mm:ss" 
timeDiff = (F.unix_timestamp('exit_time', format=timeFmt) 
     - F.unix_timestamp('entry_time', format=timeFmt)) 
new_sdf = sdf.withColumn("Dwell", timeDiff) 

任何幫助,非常感謝!

回答

0

您可以只投這樣的值在PostgreSQL中獲得時間戳:

SELECT CAST('2017-07-15T13:00:37-05:00' AS timestamp with time zone); 

     timestamptz 
------------------------ 
2017-07-15 20:00:37+02 
(1 row) 

然後使用時間戳算術和減去兩個時間戳來得到一個interval

0

SQL應該識別格式並能夠投射。從那裏你可以投射爲時間戳,然後投射爲整數秒。你可以這樣做:

SELECT 
    CAST(CAST(entry_time AS TIMESTAMP) AS INT) AS ts_seconds_entry_time, 

    CAST(CAST(exit_time AS TIMESTAMP) AS INT) AS ts_seconds_exit_time, 

    (CAST(CAST(exit_time AS TIMESTAMP) AS INT) 
    - CAST(CAST(entry_time AS TIMESTAMP) AS INT)) AS dwell_seconds