在sqlite3中读取日期时间
我正在使用Python创建一个内存中的sqlite3数据库,并且有一个时间戳的列。当我在查询中对这个列使用min()或max()时,返回的结果是字符串,而不是Python的日期时间对象。我在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.strptime()来转换字符串呢?
1 个回答
15
你需要把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()
我做了个简单的谷歌搜索,找到了这个信息。