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

How to read datetime back from sqlite as a datetime instead of string in Python?(如何从sqlite读取日期时间作为日期时间而不是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中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)
in sqlite update trigger with multiple if/Case Conditions(在具有多个IF/CASE条件的SQLite UPDATE触发器中)