【问题标题】:How To Fix DateTime type only accepts Python datetime and date objects as input in python?如何修复 DateTime 类型仅接受 Python 日期时间和日期对象作为 Python 中的输入?
【发布时间】:2020-03-03 22:06:13
【问题描述】:

我正在 Flask 中创建博客,但在创建博客文章时遇到了问题。我总是收到这个错误:

SQLite DateTime type only accepts Python datetime and date objects as input.

它显示错误来自我的 models.py 文件。

这是我的 models.py 文件:

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer,primary_key = True)
    title = db.Column(db.String(50),)
    time = db.Column(db.DateTime,nullable=False,default=str(datetime.datetime.now().strftime("%a, %b %d, %Y")))
    description = db.Column(db.Text,)
    user_id = db.Column(db.Integer,db.ForeignKey('users.id'))

    def __init__(self,title,description,user_id):
        self.title = title
        self.description = description
        self.user_id = user_id

【问题讨论】:

  • 您尝试将字符串解析为 Datetime 对象。创建一个真实的日期时间对象,例如:datetime(2012, 3, 3, 10, 10, 10)。 Duplicate

标签: python datetime flask


【解决方案1】:

不应将日期时间对象转换为字符串。应该是:

time = db.Column(db.DateTime,nullable=False,default=(datetime.datetime.now))

【讨论】:

  • 其实你不应该传递函数结果,而是函数引用:default=datetime.datetime.now
【解决方案2】:

在模型列声明中使用 Integer 类型而不是 DateTime。

time = db.Column(db.Integer,nullable=False,default=(datetime.datetime.now))

因为SQLite中没有DateTime格式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-21
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2018-08-02
    • 2021-01-22
    相关资源
    最近更新 更多