2010-12-13 62 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