我用SQLite Date Browse
App ...
当我想从datetime
列中检索timestamp
值时,SQLite会返回unicod类型...
这是我的插入代码:
def Insert(self,mode,path,vname,stime,ftime):
con = sqlite3.connect(PATH_DataBase) # @UndefinedVariable
con.execute('INSERT INTO SendList VALUES(?,?,?,?,?)',(mode,path,vname,stime,ftime))
con.commit()
con.close()
dt1 = datetime.datetime(2013,01,01,01,01,01,0)
dt2 = datetime.datetime(2015,01,01,01,01,01,0)
c = 0
for f in os.listdir('/home/abbas/test/'):
c += 1
slist.Insert(common.MODE_Bluetooth_JAVA, '/home/abbas/test/'+f,'flower'+str(c) , dt1, dt2)
现在这是我的表:
但是当我想比较starttime
和datetime.now()时,python给我错误:
TypeError: can't compare datetime.datetime to unicode
答案 0 :(得分:4)
“SQLite没有预留用于存储日期和/或时间的存储类。”参考:https://www.sqlite.org/datatype3.html
Python的sqlite3模块为datetime模块中的日期和日期时间类型提供了“默认适配器”。参考:https://docs.python.org/2/library/sqlite3.html#default-adapters-and-converters
唯一的问题是您必须确保适当地定义列。示例DDL:
import sqlite3
con = sqlite3.connect(PATH_DataBase, detect_types=sqlite3.PARSE_DECLTYPES)
con.execute('''create table if not exists SendList (
cid primary key,
mode text,
path text,
vname text,
starttime timestamp,
endtime timestamp);''')
con.commit()
con.close()
插入或选择数据的任何后续连接都必须传递sqlite3.PARSE_DECLTYPES
作为关键字参数(aka kwarg)detect_types
的值。例如:
import datetime as dt
con = sqlite3.connect(PATH_DataBase, detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute('''select
*
from
SendList
where
starttime between ? and ?
limit 10;''',
(dt.datetime(2013,1,1,0,0,0), dt.datetime(2014,12,31,23,59,59)))
results = cur.fetchall()