将日期值存储到 python3 中的 sqlite table

Storing date value into sqlite table in python3

我被这个错误困住了,很想知道你如何解决它。

背景: 我在 SQLite 中构建了一个 'Paycheck' table,它具有 date 属性、net pay 属性和 支付属性。我在 SQLite 中将 date 属性设置为 date 数据类型,并设置 netgross 属性为 integer 数据类型。

问题: 我遇到一个问题,当我尝试插入 paycheck 记录时,date 属性将存储为“1994”。问题是,当我制作存储薪水记录的功能时,我在网上看到 SQLite 中 date 数据类型的日期格式是 yyyy-mm-dd,我确定我会以那种格式插入日期,但代码 运行 没问题,但在数据库中,每次我尝试添加记录时,它都会为日期声明“1994”。

以下是所有相关代码:

import sqlite3
import datetime


def date_sql_format():
    """return date in sql DATE format"""
    return str(datetime.datetime.now().strftime("%Y-%m-%d"))


def execute(command: str):
    """Take a sql query and execute it on the database."""
    connect = sqlite3.connect("db.sqlite")
    cursor = connect.cursor()
    cursor.execute(command)
    connect.commit()
    connect.close()


def add_paycheck(date: str, net: float, gross: float):
    """Add a paycheck record to the database."""
    template = f"{date}, {net}, {gross}"
    execute(f"INSERT INTO Paycheck (Date, Net, Gross) VALUES ({template})")

我希望对此有任何反馈和建议。

将此 2020-04-22 计算为算术表达式。答案是 1994。这就是这个数字的来源。

sqlite 在内部 没有 数据类型 date。如果您查看 sqlite datatypes docAffinity Name Examples 部分,create table 语句中的类型名 DATE 会导致 NUMERIC 亲和力。所以它会计算。

将日期列的数据类型更改为文本。你可能想把 sqlite date and time functions doc 放在手边。