如何将datetime从sqlite读取为datetime而不是Python中的字符串?

问题描述:

我在Python 2.6.4中使用sqlite3模块来存储SQLite数据库中的datetime。插入它非常容易,因为sqlite会自动将日期转换为字符串。问题是,当读取它作为一个字符串回来,但我需要重建原始的datetime对象。如何执行此操作?

I'm using the sqlite3 module in Python 2.6.4 to store a datetime in a SQLite database. Inserting it is very easy, because sqlite automatically converts the date to a string. The problem is, when reading it it comes back as a string, but I need to reconstruct the original datetime object. How do I do this?

如果您使用时间戳类型声明列,那么您在三叶草中: p>

If you declare your column with a type of timestamp, you're in clover:

>>> 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 0x40fc50>
>>> c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
<sqlite3.Cursor object at 0x40fc50>
>>> c.execute('select * from foo')
<sqlite3.Cursor object at 0x40fc50>
>>> c.fetchall()
[(23, datetime.datetime(2009, 12, 1, 19, 31, 1, 40113))]

看到?两个int(对于一个声明为整数的列)和datetime(对于一个列声明的时间戳),可以在完成类型的往返行程中生存。

See? both int (for a column declared integer) and datetime (for a column declared timestamp) survive the round-trip with the type intact.