2010-12-13 37 views
7

我正在使用Python创建带有时间戳列的内存sqlite3数据库。当我在查询中对此列使用min()或max()时,该列将作为字符串而不是Python日期时间对象返回。我读了一个为正常SELECT语句提供解决方案的previous question on Stackoverflow,但如果使用max()或min(),则它不起作用。这里有一个例子:在sqlite3中回读日期时间

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

回答

13

你必须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() 

做了很好的一点谷歌搜索,发现this message

+0

适合我,谢谢! – del 2010-12-13 23:43:33

相关问题