【问题标题】:Insert datetime entry into table with TIMESTAMP data type将日期时间条目插入到具有 TIMESTAMP 数据类型的表中
【发布时间】:2019-10-06 20:56:54
【问题描述】:

我正在尝试创建一个系统(使用不和谐机器人,但这与此无关),其中列出了用户的违规行为,例如发生的时间、地点、原因等,我想要一个“日期”数据类型记录它发生的时间戳。

我尝试将 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))

我最终得到一个TypeError: Bad binding argument type supplied - argument #1: type datetime.datetime 错误

【问题讨论】:

  • 您使用的是哪个数据库:mysql、oracle、sql-server,...?请在您的问题中添加相关标签。

标签: python sql date datetime apsw


【解决方案1】:

从create table语句的语法(AUTOINCREMENT不带下划线)和apsw标签,我怀疑你使用的是SQLite数据库。

如果您希望将当前时间戳插入timestamp 列,我的第一个建议是直接在 SQL 中执行此操作,而不是使用在 python 中生成的变量。在 sqlite 中,CURRENT_TIMESTAP 为您提供当前日期/时间作为时间戳:

warns.execute(
    "INSERT INTO warns (wdate, server, user, author, reason) VALUES (CURRENT_TIMESTAMP, ?, ?, ?, ?)", 
    (guild, user, author, reason)
)

另一个可以进一步简化代码的选项是在创建表时为时间戳列设置默认值。然后,您可以在插入时忽略此列,并放心分配正确的值:

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)
        )

注意:date 不是一个合理的列名,因为它与数据类型名冲突。我在上面的所有代码中将它重命名为wdate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2013-01-11
    • 2022-01-06
    • 2019-04-19
    • 2015-02-19
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多