简体   繁体   English

在sqlite3中读回日期时间

[英]Reading back a datetime in sqlite3

I am using Python to create an in-memory sqlite3 database with a timestamp column. 我正在使用Python创建一个带有时间戳列的内存中sqlite3数据库。 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. 当我在查询中对此列使用min()或max()时,该列将作为字符串而不是Python datetime对象返回。 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. 我读了一个关于Stackoverflow上一个问题,问题提供了普通SELECT语句的解决方案,但是如果使用max()或min()则它不起作用。 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,)]

Is there any way to fetch a proper datetime object, without manually converting the string using datetime.strptime() after fetching it? 有没有办法获取正确的日期时间对象,而不是在获取后使用datetime.strptime()手动转换字符串?

You have to set detect_types to sqlite.PARSE_COLNAMES and use as "foo [timestamp]" like this: 你必须将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()

Did a nice little Google search and found this message . 做了一个不错的小谷歌搜索,发现了这条消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM