PostgreSQL获取时间戳之间的时间差

3
我查看了许多与此相关的SO问题,但似乎没有任何一种方法能够奏效。我不太擅长半复杂的SQL查询。
我想要获取当前时间和一个以Unix时间戳表示的列之间的差值(以小时为单位)。
我不确定我做对了什么或做错了什么。目标是只检索小于24小时的行。如果有更好的方法或示例可以使用,那将是很好的。
我尝试了这里Timestamp Difference In Hours for PostgreSQL中的几个答案。
无论我如何尝试,都无法使这个查询起作用。wc.posted是一个存储为Unix时间戳的bigint。
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:

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个回答

2

来自优秀手册

还提供了单参数的to_timestamp函数;它接受一个double precision参数并从Unix纪元时间(1970-01-01 00:00:00+00后的秒数)转换为带有时区的timestamp。(整数的Unix纪元时间会被隐式转换为double precision。)

因此,要将您的bigint秒数转换为timestampz

to_timestamp(wc.posted)

也许你在寻找这个:

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

太好了。谢谢,我猜那个手册非常有帮助。但是我还不太明白需要使用那个函数进行转换。感谢你指出这一点。 - Panama Jack

1

尝试:

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

细节在这里: EXTRACT

请在SQL Fiddle中发布您的查询。 - Vignesh Kumar A

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;

除了使用转换函数,你还可以这样做:now()::timestamp - your_time_field::timestamp - Zoran777

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接