如何从sqlite读取日期时间作为日期时间而不是Python中的字符串?

2021-12-08 00:00:00 python datetime sqlite

我使用 Python 2.6.4 中的 sqlite3 模块在 SQLite 数据库中存储日期时间.插入它非常容易,因为sqlite 会自动将日期转换为字符串.问题是,在读取它时它会作为字符串返回,但我需要重建原始的 datetime 对象.我该怎么做?

解决方案

如果你用时间戳类型声明你的列,你就是在三叶草中:

<预><代码>>>>db = sqlite3.connect(':memory:',detect_types=sqlite3.PARSE_DECLTYPES)>>>c = db.cursor()>>>c.execute('create table foo (bar integer, baz timestamp)')<sqlite3.Cursor 对象在 0x40fc50>>>>c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))<sqlite3.Cursor 对象在 0x40fc50>>>>c.execute('select * from foo')<sqlite3.Cursor 对象在 0x40fc50>>>>c.fetchall()[(23, datetime.datetime(2009, 12, 1, 19, 31, 1, 40113))]

看到了吗?int(对于声明为整数的列)和 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?

解决方案

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))]

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

相关文章