我有一个.txt文件,可用于填写sqlite表FoodConsumed_tb
class FoodConsumed_Tb(db.Model):
__tablename__ = 'foodconsumed_tb'
id = db.Column(db.Integer, primary_key=True)
date_created = db.Column(db.DateTime)
item = db.Column(db.String(200), nullable=False)
nutritionalvalue_id = db.Column(db.Integer, ForeignKey('nutritionalvalues.id'))
amount = db.Column(db.Float, nullable=False)
作者
p.communicate(b"""
INSERT INTO foodconsumed_tb
(date_created,
item,
amount,
);
.separator ","
.import ate_records.txt foodconsumed_tb
""")
ate_records.txt看起来像
1,2019-08-24,Broccoli Chinese,17,1.57
2,2019-08-24,chia seeds,11,0.20
3,2019-08-24,flax seeds,25,0.20
4,2019-08-24,sunflower seeds,26,0.30
....
这有效,并且该表填充了所有记录。但是当我尝试使用
使用此表时consumedfoods = FoodConsumed_Tb.query.order_by(FoodConsumed_Tb.date_created).all()
我得到了错误
ValueError: Couldn't parse datetime string: '2019-08-24'
对于通过表单(我正在制作烧瓶应用程序)输入表格的日期
date_created=datetime.strptime(date, "%Y-%m-%d").date()
其中“日期”来自form.request ['date'],在格式化日期时效果很好。
但是当我只是将所有记录从.txt文件导入表中时,我不知道如何格式化日期?
我一直在尝试
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SECRET_KEY'] = 'secret'
db = SQLAlchemy(app)
from app import FoodConsumed_Tb
rows = FoodConsumed_Tb.query.all()
for row in rows:
consumed_food_entry_to_update = FoodConsumed_Tb.query.get_or_404(row.id)
consumed_food_entry_to_update.date_created = datetime.strptime(consumed_food_entry_to_update.date_created, "%Y-%m-%d").date()
db.session.commit()
但它说
ValueError: Couldn't parse datetime string: '2019-08-24'
答案 0 :(得分:0)
这是格式错误。
您的日期类型为'date_created = db.Column(db.DateTime)',您 应该插入值'datetime('now')'
如果您的数据类型为“ db.Column(db.Date)”,则该值应为 'date('now')'
datetime -> 2020-04-02 14:30:21
date -> 2020-04-02