[英]Insert datetime entry into table with TIMESTAMP data type
I am trying to create a system (with a discord bot, but that's not relevant to this) where it lists infractions of a user, like when it happened, where, why, etc. and I want a "date" datatype that logs the timestamp that it happened.我正在尝试创建一个系统(使用 discord 机器人,但这与此无关),其中列出了用户的违规行为,例如发生的时间、地点、原因等,并且我想要一个“日期”数据类型来记录它发生的时间戳。
I tried having the DATE
datatype to be "timestamp" (as well as "datetime", but the same error happens)我尝试将
DATE
数据类型设置为“时间戳”(以及“日期时间”,但发生同样的错误)
conn1 = apsw.Connection('./dbs/warns.db')
warns = conn1.cursor()
warns.execute(
"""
CREATE TABLE IF NOT EXISTS warns
(id INTEGER PRIMARY KEY AUTOINCREMENT,
date timestamp,
server string,
user string,
author string,
reason string)
"""
)
def add_warn(guild: str, user: str, author: str, reason):
now = datetime.datetime.utcnow()
with conn1:
warns.execute("INSERT INTO warns (date, server, user, author, reason) VALUES (?, ?, ?, ?, ?)", (now, guild, user, author, reason))
I end up getting a TypeError: Bad binding argument type supplied - argument #1: type datetime.datetime
error我最终得到一个
TypeError: Bad binding argument type supplied - argument #1: type datetime.datetime
错误
From the syntax of the create table statement ( AUTOINCREMENT
without an underscore) and the apsw
tag, I suspect that you are using a SQLite database.从 create table 语句(不带下划线的
AUTOINCREMENT
)和apsw
标签的语法来看,我怀疑您使用的是 SQLite 数据库。
If you are looking to insert the current timestamp to a timestamp
column, my first suggestion is to do it directly in SQL, instead of using a variable generated in python.如果您希望将当前时间戳插入
timestamp
列,我的第一个建议是直接在 SQL 中执行此操作,而不是使用在 python 中生成的变量。 In sqlite, CURRENT_TIMESTAP
gives you the current date/time as a timestamp:在 sqlite 中,
CURRENT_TIMESTAP
为您提供当前日期/时间作为时间戳:
warns.execute(
"INSERT INTO warns (wdate, server, user, author, reason) VALUES (CURRENT_TIMESTAMP, ?, ?, ?, ?)",
(guild, user, author, reason)
)
Another option, that would furthermore simplify your code, is to set a default for the timestamp column when creating the table.另一个可以进一步简化代码的选项是在创建表时为时间戳列设置默认值。 Then, you can just ignore this column when inserting, and rest assured that the correct value will be assigned:
然后,您可以在插入时忽略此列,rest 保证将分配正确的值:
warns.execute(
"""
CREATE TABLE IF NOT EXISTS warns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
wdate timestamp DEFAULT CURRENT_TIMESTAMP,
server string,
user string,
author string,
reason string
)
"""
)
def add_warn(guild: str, user: str, author: str, reason):
with conn1:
warns.execute(
"INSERT INTO warns (server, user, author, reason) VALUES (?, ?, ?, ?)",
(now, guild, user, author, reason)
)
Note: date
is not a sensible column name, since it clashes with a datatype name.注意:
date
不是一个合理的列名,因为它与数据类型名称冲突。 I renamed it wdate
in all the above code.我在上面的所有代码中将其重命名为
wdate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.