如何通过python从postgreSQL获取并比较两个时间戳值?
我目前正在使用psycopg2和python与postgreSQL数据库交互。我在一个名为“test”的数据库中,有两个表:“test1”和“test2” 每个表中有一行,该行有两列:如何通过python从postgreSQL获取并比较两个时间戳值?,python,postgresql,timestamp,comparison,Python,Postgresql,Timestamp,Comparison,我目前正在使用psycopg2和python与postgreSQL数据库交互。我在一个名为“test”的数据库中,有两个表:“test1”和“test2” 每个表中有一行,该行有两列: 日期,它具有当前的_日期值 Timestamp,它具有当前的_Timestamp值 我使用以下代码搜索它: """SELECT timestamp FROM test1 WHERE date = '2014-07-16';""" 如果我输入这个,终端会给出: timestamp
- 日期,它具有当前的_日期值
- Timestamp,它具有当前的_Timestamp值
"""SELECT timestamp
FROM test1
WHERE date = '2014-07-16';"""
如果我输入这个,终端会给出:
timestamp
----------------------------
2014-07-16 16:10:22.380059
(1 row)
现在,我想看看一个时间戳,让我的程序告诉我它是否比另一个时间戳大30分钟。然而,我在获取这些值以在python中使用时遇到了困难,并且弄清楚比较通常是如何工作的。我对postgreSQL完全陌生,所以我不太熟悉它的语法,所以我在尝试将SELECT命令的结果分配给变量时遇到了很多麻烦,然后我可以使用python进行比较
感谢您的任何帮助
谢谢。我只在MySQL中使用了Python,但postgreSQL: 现在,从文档中可以看出,从DB中检索到的时间戳可以自动转换为Python中的datetime对象,这很方便。但即使以字符串形式给出,这也不是问题:
>>> from datetime import datetime
>>> import time
>>> d = datetime.strptime('2014-07-16 16:10:22.380059', '%Y-%m-%d %H:%M:%S.%f')
>>> time.mktime(d.timetuple())
1405483822.0
将两个日期时间转换为时间戳,然后减去以检查差值是否大于1800(30*60)秒。过程中会损失微秒,但可能不需要这种粒度级别。因为在这种情况下,您知道要在Postgres和同一数据库中比较的两个值,所以我建议使用纯SQL进行比较 i、 e 鉴于这些表格:
create table foo
(
id serial,
created timestamp without time zone
);
create table bar
(
id serial,
created timestamp without time zone
);
这些数据:
insert into foo (created) VALUES
('2014-07-16 16:10:22.380059'),
('2014-07-16 17:10:21.480048'),
('2014-07-16 16:32:23.580037');
insert into bar (created) VALUES
('2014-07-16 16:44:22.380059'),
('2014-07-16 17:15:21.480048'),
('2014-07-16 16:38:23.580037');
您可以查询此表单:
select ( (select created from bar order by id limit 1) -
(select created from foo order by id limit 1)
) > interval '30 minutes' as time_diff;
您如何获得每一列的详细信息可以根据您的需要而有所不同
然后在Python代码中,返回0(如果不是>30分钟)或1(如果是>30分钟)
您可以使用该库很好地比较时间戳。您能展示一些示例行吗?好的,很好,这是我正在寻找的cur.fetchone()命令。谢谢
select ( (select created from bar order by id limit 1) -
(select created from foo order by id limit 1)
) > interval '30 minutes' as time_diff;