PostgreSQL在时间戳之间得到时间差

时间:2014-01-18 04:47:22

标签: sql postgresql timestamp

我看过很多与此相关的问题,但我似乎无法解决任何问题。半复杂的SQL查询我不是很好。

我希望得到当前时间与以小时为单位的unix时间戳列之间的差异。

我不确定我做错了什么或对此事做对。目标是仅拉出小于24小时的行。如果有更好的方法或示例有效那就太棒了。

我从这里Timestamp Difference In Hours for PostgreSQL

尝试了几个答案

无论我尝试多少种不同的方式,我都无法使用此查询。 wc.posted是一个bigint商店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'

然后错误:

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

这是一个简化的fiddle

4 个答案:

答案 0 :(得分:1)

尝试:

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

此处的详细信息:EXTRACT

答案 1 :(得分:1)

来自fine manual

  

单参数to_timestamp功能也可用;它接受double precision参数并从Unix纪元(自1970-01-01 00:00:00 + 00以来的秒数)转换为timestamp with time zone。 (Integer Unix时期被隐式转换为double precision。)

所以要将bigint秒 - 自 - 纪元转换为timestampz

to_timestamp(wc.posted)

也许你正在寻找这个:

WHERE to_timestamp(wc.posted) > current_timestamp - interval '24 hours'

答案 2 :(得分:0)

尝试这一点我相信这会对你有所帮助

select field_1,field_2,field_3 from schema_name.table_name Where  
ROUND(EXTRACT(EPOCH FROM (cast(now() as timestamp)  - cast(your_time_field as timestamp)))/60) > 1440;

答案 3 :(得分:0)

错误消息:

  

提示:没有函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。

实际上,最简单的解决方案是添加显式时间戳类型转换

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::timestamp)) > current_timestamp - interval '24 hours'

注意演员:

wc.posted::timestamp