[英]Timestamp comparison with python mysql.connector
I'm trying to do a timestamp comparison with mysql.connector in Python3.我正在尝试与 Python3 中的 mysql.connector 进行时间戳比较。 For some reason I've got an empty result with the following query:
出于某种原因,我得到了以下查询的空结果:
SELECT timestamp, reading, value FROM history where device='dht22' and timestamp > now() - interval 6 hour
If I switch the operator to "<" the query works and shows all the results, older than 6 hours ago, but it's not what I want.如果我将运算符切换为“<”,则查询有效并显示 6 小时前的所有结果,但这不是我想要的。 I want to show the results from the past 6 hours only.
我只想显示过去 6 小时的结果。
If I execute the query directly in mysql, it works as expected, but in python it doesn't.如果我直接在 mysql 中执行查询,它会按预期工作,但在 python 中它不会。 How can I go around this?
我该如何解决这个问题?
My current python code is like so:我当前的python代码是这样的:
import mysql.connector
cnx = mysql.connector.connect(user='user', password='pass',
host='127.0.0.1',
database='db')
cur = cnx.cursor()
query="SELECT `timestamp`, `reading`, `value` FROM history where device='dht22' and `timestamp` > now() - interval 6 hour"
cur.execute(query)
rows=cur.fetchall()
for row in rows:
print(row)
cur.close()
cnx.close()
[UPDATE] I found the problem. [更新]我发现了问题。 I was connecting to the MySQL server though "localhost" and for some reason (bad configuration probably), it was not parsing timestamp comparison correctly.
我通过“localhost”连接到 MySQL 服务器,由于某种原因(可能是配置错误),它没有正确解析时间戳比较。 When I put the full domain name in the connection object, all works fine.
当我将完整的域名放入连接对象时,一切正常。 Really weird!
真的很奇怪!
use BETWEEN之间使用
SELECT `timestamp`, reading, value FROM history WHERE device='dht22' AND `timestamp` BETWEEN NOW() - INTERVAL 6 hour AND NOW()
create table history( id int primary key, reading int, value varchar(19), device VARCHAR(10), `timestamp` datetime ); INSERT INTO history VALUES (1,1,'test','dht22', NOW() - INTERVAL 5 HOUR) ,(2,1,'test','dht22', NOW() - INTERVAL 2 HOUR) ,(3,1,'test','dht22', NOW() - INTERVAL 7 HOUR)
SELECT `timestamp`, reading, value FROM history WHERE device='dht22' AND `timestamp` BETWEEN NOW() - INTERVAL 6 hour AND NOW()
\ntimestamp |时间戳 | reading |
阅读| value
价值\n:------------------ |
:------------------ | ------: |
------: | :----
:----\n2020-08-23 14:30:04 |
2020-08-23 14:30:04 | 1 |
1 | test
测试 \n2020-08-23 17:30:04 |
2020-08-23 17:30:04 | 1 |
1 | test
测试 \n
And also my select还有我的选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.