在 sqlite3 中读回日期时间
我正在使用 Python 创建一个带有时间戳列的内存 sqlite3 数据库.当我在查询中对该列使用 min() 或 max() 时,该列将作为字符串而不是 Python 日期时间对象返回.我读了 关于 Stackoverflow 的上一个问题为普通的 SELECT 语句提供了解决方案,但如果使用 max() 或 min() 则不起作用.这是一个例子:
I am using Python to create an in-memory sqlite3 database with a timestamp column. When I use min() or max() on this column in my query, the column is returned as a string rather than a Python datetime object. I read a previous question on Stackoverflow that provided a solution for normal SELECT statements, but it doesn't work if max() or min() is used. Here's an example:
>>> 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',)]
我尝试将结果转换为时间戳,但它只返回年份:
I tried to cast the result to a timestamp but it only returns the year:
>>> c.execute('select cast(max(baz) as timestamp) from foo')
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.fetchall()
[(2010,)]
有什么方法可以获取正确的 datetime 对象,而无需在获取后使用 datetime.strptime() 手动转换字符串?
Is there any way to fetch a proper datetime object, without manually converting the string using datetime.strptime() after fetching it?
推荐答案
你必须将 detect_types 设置为 sqlite.PARSE_COLNAMES 并使用 as "foo [timestamp]"
像这样:
You have to set detect_types to sqlite.PARSE_COLNAMES and use as "foo [timestamp]"
like this:
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()
做了一个很好的谷歌搜索,发现 这条消息.
Did a nice little Google search and found this message.
相关文章