本文介绍了python sqlite ValueError:无法解析日期时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt文件,可用来填写sqlite表FoodConsumed_tb

I have a .txt file which I use to fill a sqlite table 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看起来像

the ate_records.txt looks like

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

这有效,并且该表填充了所有记录.但是当我尝试使用

This works and the table is filled with all the records. But when I come and try and use this table using

consumedfoods = FoodConsumed_Tb.query.order_by(FoodConsumed_Tb.date_created).all()

我得到了错误

ValueError: Couldn't parse datetime string: '2019-08-24'

对于通过表单(我正在创建烧瓶应用程序)输入到表格中的日期

For dates that get entered into the table via a form (I'm making a flask app) I use

date_created=datetime.strptime(date, "%Y-%m-%d").date()

其中日期"来自form.request ['date'],在格式化日期时工作正常.

where 'date' comes from form.request['date'], works fine as I'm formatting the date.

但是当我只是将所有记录从.txt文件导入表中时,我不知道如何格式化日期?

But when I just import the all the records into the table from a .txt file, I don't know how to format the date?

我一直在尝试

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'

推荐答案

这是格式错误.

  1. 您的日期类型为'date_created = db.Column(db.DateTime)',您应该插入值'datetime('now')'

  1. your date type is 'date_created = db.Column(db.DateTime)', youshould insert value 'datetime('now')'

如果您的数据类型为'db.Column(db.Date)',则该值应为'date('now')'

if your data type is 'db.Column(db.Date)', then the value should be 'date('now')'

datetime -> 2020-04-02 14:30:21
date -> 2020-04-02

这篇关于python sqlite ValueError:无法解析日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:57