我正在使用 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() 手动转换字符串?