Python valueError:无法分析datetime字符串:在sq中使用单引号

2024-04-24 00:50:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将数据从一个txt文件导入到一个表中,该文件如下所示:

 1,2019-8-24,Broccoli Chinese,17,1.57 
 2,2019-8-24,chia seeds,11,0.20
 3,2019-8-24,flax seeds,25,0.20
 4,2019-8-24,sunflower seeds,26,0.30

在python shell中打印表时,我得到:

(1, '2019-8-24', 'Broccoli Chinese', 17, 1.57)
(2, '2019-8-24', 'chia seeds', 11, 0.2)
(3, '2019-8-24', 'flax seeds', 25, 0.2)
(4, '2019-8-24', 'sunflower seeds', 26, 0.3)

后来在使用这个表时,我会遇到如下错误

valueError: Couldn't parse datetime string: '2019-8-24'

这些单引号“”实际上在表条目中吗?就像在实际的表中一样,它是'2019-8-24'还是仅仅是2019-8-24,当我打印出行时,它会添加''。你知道吗

我只是在整理valueError时遇到了问题,并且想知道是否在导入期间表中的日期前后输入了单引号“”,可能需要删除?你知道吗

编辑

这是由于错误而无法运行的实际代码

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

Tags: 文件tofromimportappdbdatetimedate
1条回答
网友
1楼 · 发布于 2024-04-24 00:50:55

我猜您的SQL版本不喜欢月份是个位数。您可以尝试自己使用Python清除这些数据,例如

def repl(m):
    year = m.group(1)
    month = m.group(2).zfill(2)
    day = m.group(3).zfill(2)

    return year + '-' + month + '-' + day

date = '2019-8-24'
date_new = re.sub('(\d+)-(\d+)-(\d+)', repl, date)
print(date)
print(date_new)

这张照片:

2019-8-24
2019-08-24

我在这里所做的就是用左边的零将月和日的分量填充到两位数。我没费心去碰年份,假设你不期待任何中世纪的数据。你知道吗

相关问题 更多 >