python sqlite ValueError: Couldn't parse datetime string

落爺英雄遲暮 提交于 2020-04-30 05:39:32

问题


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)

by

p.communicate(b"""
INSERT INTO foodconsumed_tb
         (date_created,
          item,
          amount,
         );
.separator ","
.import ate_records.txt foodconsumed_tb
""")

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()

I get the error

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()

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

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?

I've been trying this

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()

but it says

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

回答1:


this is format error.

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

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


来源:https://stackoverflow.com/questions/58388332/python-sqlite-valueerror-couldnt-parse-datetime-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!