How to read datetime back from sqlite as a datetime instead of string in Python?(如何从sqlite读取日期时间作为日期时间而不是Python中的字符串?)
问题描述
我使用 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.
这篇关于如何从sqlite读取日期时间作为日期时间而不是Python中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从sqlite读取日期时间作为日期时间而不是Python中的字符串?
基础教程推荐
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
