2015-02-06 62 views
0

的问题sqlite3的,选择与日期时间

我试图做一个sqlite3的查询,在Python中,在WHERE部分使用日期时间。

placedDate是datetime对象,我的代码如下。出于某种原因,查询返回今天放置的项目,而不是放在最后一小时的投注。什么可能是错的?

sql = r"""SELECT count(*) FROM bet WHERE placedDate>?""" 
    td = timedelta(minutes=60) 
    dt = datetime.utcnow()-td 
    with closing(conn.cursor()) as cur: 
     cur.execute(sql, (dt,)) 
     print cur.fetchone()[0] 

我也曾尝试

sql = r"""SELECT count(*) FROM bet WHERE placedDate>datetime(?)""" 

一个例子placedDate是

'placedDate': u'2015-02-06T01:20:37.000Z', 

表定义

使用

meta = conn.execute("PRAGMA table_info('bet')") 
    print('bet table info:') 
    for r in meta: 
     print r 

我得到

(0, u'id', u'INTEGER', 0, None, 1) 
(1, u'marketId', u'varchar', 0, None, 0) 
(2, u'sizeMatched', u'decimal(10,2)', 0, None, 0) 
(3, u'orderType', u'varchar', 0, None, 0) 
(4, u'selectionId', u'int', 0, None, 0) 
(5, u'price', u'decimal(5,2)', 0, None, 0) 
(6, u'persistenceType', u'varchar', 0, None, 0) 
(7, u'size', u'decimal(10,2)', 0, None, 0) 
(8, u'placedDate', u'datetime', 0, None, 0) 
(9, u'averagePriceMatched', u'decimal(10,2)', 0, None, 0) 
(10, u'side', u'varchar', 0, None, 0) 
(11, u'description', u'varchar', 0, None, 0) 
+0

请向我们展示表格定义。 – deets 2015-02-06 22:23:38

+1

表定义不起作用,因为SQLite [使用动态类型](http://www.sqlite.org/datatype3.html)。表格中日期值的格式是什么? – 2015-02-07 07:52:33

+0

CL - 你是否说我需要在存储日期之前转换为日期时间?我想我在插入语句中使用字符串 – Ginger 2015-02-07 11:10:52

回答

0

这个工作对我来说:

import sqlite3 
from datetime import datetime, timedelta 

conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) 


c = conn.cursor() 

c.execute(""" 
CREATE TABLE test (
    foo varchar, 
    ts datetime 
);""") 

rowcount = c.execute("SELECT COUNT(*) FROM test").fetchone()[0] 
assert 0 == rowcount, rowcount 

dt = timedelta(minutes=5) 

now = datetime.now() 

then = now 

for i in xrange(100): 
    then -= dt 
    c.execute("INSERT INTO test VALUES(?, ?)", (str(i), then)) 

rowcount = c.execute("SELECT COUNT(*) FROM test").fetchone()[0] 
assert 100 == rowcount, rowcount 


hour_ago = now - timedelta(minutes=60) 
rowcount = c.execute(
    "SELECT COUNT(*) FROM test WHERE ts >= ?", 
    (hour_ago,)).fetchone()[0] 
assert 12 == rowcount, rowcount 

如果是你,我怀疑该数据比你的期望不同。