del*_*del 7 python sqlite datetime timestamp
我正在使用Python创建一个带有时间戳列的内存中sqlite3数据库.当我在查询中对此列使用min()或max()时,该列将作为字符串而不是Python datetime对象返回.我读了一个关于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',)]
Run Code Online (Sandbox Code Playgroud)
我试图将结果转换为时间戳,但它只返回年份:
>>> c.execute('select cast(max(baz) as timestamp) from foo')
<sqlite3.Cursor object at 0x7eff420e0be0>
>>> c.fetchall()
[(2010,)]
Run Code Online (Sandbox Code Playgroud)
有没有办法获取正确的日期时间对象,而不是在获取后使用datetime.strptime()手动转换字符串?
Joe*_*gen 14
你必须将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()
Run Code Online (Sandbox Code Playgroud)
做了一个不错的小谷歌搜索,发现了这条消息.
| 归档时间: |
|
| 查看次数: |
3740 次 |
| 最近记录: |