我正在尝试将日期和时间插入到sqlite表中。
这是我的代码。
import sqlite3
from datetime import datetime
### Date Time ###
dt = datetime.now()
dates = dt.date()
times = dt.time()
def sql(date, time):
### CREATE DB
con = sqlite3.connect("date.db")
cur = con.cursor()
## CREATE TABLE
cur.execute("CREATE TABLE if NOT EXISTS d_t (datee, timee)")
con.commit()
## INSERT DATA
cur.execute("INSERT INTO d_t (datee, timee) VALUES (?,?)", (date, time))
con.commit()
## VIEW DATA
cur.execute("SELECT * from d_t")
row = cur.fetchall()
print(type((row[0][0]))) # Printing_Date_only
sql(dates, times)但这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\Hridoy\Documents\GitHub\Covid19\datedb.py", line 26, in <module>
sql(dates, times)
File "C:\Users\Hridoy\Documents\GitHub\Covid19\datedb.py", line 18, in sql
cur.execute("INSERT INTO d_t (datee, timee) VALUES (?,?)", (date, time))
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.我不想以字符串的形式插入日期和时间,因为稍后我需要比较两个日期,其中一个日期将来自数据库。
请寻找这个问题的解决方案。
发布于 2021-09-15 14:40:11
在尝试存储日期/时间时,使用SQLite可能有点棘手,而且我认为您不能存储时间(没有日期)。为什么不将日期和时间存储在一起作为完整的日期时间值呢?
下面的代码存储datetime值并修改sqlite3.connect()调用,以便更好地处理datetime (我们将在查询数据库时得到一个datetime )。在创建表时,我们还需要将d_t表的"date_time“列的类型指定为SQLite时间戳。
import sqlite3
from datetime import datetime
### Date Time ###
dt = datetime.now()
def sql(dt_value):
### CREATE DB
con = sqlite3.connect("date.db", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
## CREATE TABLE
cur.execute("CREATE TABLE if NOT EXISTS d_t (date_time timestamp)")
con.commit()
## INSERT DATA
cur.execute("INSERT INTO d_t (date_time) VALUES (?)", (dt_value,))
con.commit()
## VIEW DATA
cur.execute("SELECT * from d_t")
row = cur.fetchall()
print(type(row[0][0])) # Print type of datetime
print(row[0][0]) # Print datetime
print(row[0][0].date()) # Print date
print(row[0][0].time()) # Print time
sql(dt)作为另一种解决方案,您可能还想尝试我编写的"easy_db“库来帮助解决这类问题。只需使用pip安装它:
pip install easy_db然后我们可以用更少/更干净的代码来完成同样的任务。
import easy_db
from datetime import datetime
### Date Time ###
dt = datetime.now()
def insert_and_read_datetime(dt_value):
# Create and connect to SQLite database
db = easy_db.DataBase("date.db")
# Create "d_t" table and add one row of data to it
# From our input dictionary, a "date" column is automatically created and
# this column is given the SQLite timestamp type based on the type of dt_value
db.append("d_t", {"date": dt_value})
# Run a SELECT * query to pull the full "d_t" table
# Returned data is a list with a dictionary for each row
data = db.pull("d_t")
print(type(data[0]["date"])) # Print type of datetime
print(data[0]["date"]) # Print datetime
print(data[0]["date"].date()) # Print date
print(data[0]["date"].time()) # Print time
insert_and_read_datetime(dt)祝你的新冠肺炎项目好运!
https://stackoverflow.com/questions/67319288
复制相似问题