小时x和小时y之间的Sqlite3

时间:2016-12-19 19:51:12

标签: python datetime sqlite

希望构建一个在过去24小时内逐小时检索行的查询。我的问题更多的是关于为什么一种方法有效而另一种方法无效。我找不到明确的答案。

使用:

SELECT date, temp 
FROM dht_temps 
WHERE zone = 'outside' 
 and temp <> 0 and date BETWEEN "2016-12-19 04:00:00" AND "2016-12-19 08:00:00"

不起作用:

SELECT date, temp FROM dht_temps 
WHERE zone = 'outside' and temp <> 0 
  and date BETWEEN date('now','-2 hours') 
  AND date('now','-1 hours')

对我来说,两者都应该产生相同的结果,但这就是我成为黑客的原因。我想了解原因。感谢

1 个答案:

答案 0 :(得分:1)

您应该致电datetime(),而不是date()。请注意,在下面的示例中,使用date()获取零结果时,如何使用datetime()获取一个结果。

import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute('create table dht_temps (date TEXT, temp INTEGER, zone TEXT)')
conn.execute('insert into dht_temps values(datetime("now"), 4, "outside")')
conn.execute('insert into dht_temps values(datetime("now", "-30 minutes"), 1, "outside")')
conn.execute('insert into dht_temps values(datetime("now", "-90 minutes"), 2, "outside")')
conn.execute('insert into dht_temps values(datetime("now", "-150 minutes"), 3, "outside")')
l1 = list(conn.execute("""
SELECT date, temp FROM dht_temps 
WHERE zone = 'outside' and temp <> 0 
  and date BETWEEN date('now','-2 hours') 
  AND date('now','-1 hours')
"""))

l2 = list(conn.execute("""
SELECT date, temp FROM dht_temps 
WHERE zone = 'outside' and temp <> 0 
  and date BETWEEN datetime('now','-2 hours') 
  AND datetime('now','-1 hours')
"""))

assert len(l1) == 0
assert len(l2) == 1