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

2023-10-10数据库问题
9

本文介绍了如何从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中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL GROUP BY DateTime +/- 3 秒
MySQL GROUP BY DateTime +/- 3 seconds(MySQL GROUP BY DateTime +/- 3 秒)...
2024-04-16 数据库问题
14

如何在MySQL中为每个组选择第一行?
How to select the first row for each group in MySQL?(如何在MySQL中为每个组选择第一行?)...
2024-04-16 数据库问题
13

MySQL - 获取最低值
MySQL - Fetching lowest value(MySQL - 获取最低值)...
2024-04-16 数据库问题
8

在 cmakelist.txt 中添加和链接 mysql 库
Add and link mysql libraries in a cmakelist.txt(在 cmakelist.txt 中添加和链接 mysql 库)...
2024-04-16 数据库问题
41

考勤数据库的良好数据库设计(架构)是什么?
What is a good database design (schema) for a attendance database?(考勤数据库的良好数据库设计(架构)是什么?)...
2024-04-16 数据库问题
7