我正在使用Python创建一个带有时间戳列的内存中sqlite3数据库。当我在查询中对此列使用min()或max()时,该列将作为字符串而不是Python datetime对象返回。我读了一个previous question on Stackoverflow,为正常的SELECT语句提供了解决方案,但如果使用max()或min()则不起作用。这是一个例子:
>>> db = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
>>> c = db.cursor()
>>> c.execute('create table foo (bar integer, baz timestamp)')
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.execute('select * from foo')
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.fetchall()
[(23, datetime.datetime(2010, 12, 14, 1, 15, 54, 685575))]
>>> c.execute('select max(baz) from foo')
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.fetchall()
[(u'2010-12-14 01:15:54.685575',)]
我尝试将结果转换为时间戳,但它只返回年份:
>>> c.execute('select cast(max(baz) as timestamp) from foo')
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.fetchall()
[(2010,)]
有没有办法获取正确的datetime对象,而不是在获取后使用datetime.strptime()手动转换字符串?
答案 0 :(得分:14)
您必须将detect_types设置为sqlite.PARSE_COLNAMES并使用as "foo [timestamp]"
,如下所示:
import sqlite3
import datetime
db = sqlite3.connect(':memory:', detect_types = sqlite3.PARSE_COLNAMES)
c = db.cursor()
c.execute('create table foo (bar integer, baz timestamp)')
c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
c.execute('insert into foo values(?, ?)', (42, datetime.datetime.now() + datetime.timedelta(-1)))
c.execute('select bar, baz as "ts [timestamp]" from foo')
print c.fetchall()
c.execute('select max(baz) as "ts [timestamp]" from foo')
print c.fetchall()
进行了一次不错的Google搜索并找到了this message。