2

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 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.