SQLAlchemy db.session.commit() 报错 SQLite DateTime type only accepts Python datetime and date objects as input

代码如下,我在flask shell下定义 m = Message(name=‘L’, content=‘db.test’, timestamp=‘2024-08-14 12:17:30’), 执行db.session.commit()报错

sqlalchemy.exc.PendingRollbackError: This Session’s transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (builtins.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
[SQL: INSERT INTO message (name, content, timestamp) VALUES (?, ?, ?)]
[parameters: [{‘timestamp’: ‘2024/8/14 19:56:24’, ‘content’: ‘hello’, ‘name’: ‘LLL’}]] (Background on this error at: Error Messages — SQLAlchemy 2.0 Documentation)

class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    content = db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.String(20), nullable=False)

timestamp应该是一个特殊值名称,不能使用,我将timestamp改为time即可

看报错是你之前定义的 timestamp 的类型是 db.DateTime(现在是 db.String),但是在 shell 里写入的字符串,所以报错了。可以试一下重新生成数据库表。