简体   繁体   English

sqlite3,以日期时间选择

[英]sqlite3, selects with datetime

The Problem 问题

I am trying to do a sqlite3 query, in Python, using a datetime in the WHERE section. 我正在尝试使用WHERE部分中的datetime在Python中执行sqlite3查询。

The placedDate is datetime object, and my code is below. PlacedDate是datetime对象,下面是我的代码。 For some reason, the query returns items placed today, rather than bets placed in the last hour. 由于某种原因,查询返回的是今天放置的项目,而不是最后一小时的投注。 What could be wrong? 有什么事吗

    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]

I have also tried 我也尝试过

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

An example placedDate is 例如placedDate是

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

Table Definition 表定义

Using 使用

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

I get 我懂了

(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)

This works for me: 这对我有用:

 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

If it does for you, I suspect the data being different than your expectation. 如果对您有用,我怀疑数据与您的期望不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM