【问题标题】:Date format error while inserting values from CSV file into database using python使用python将CSV文件中的值插入数据库时​​出现日期格式错误
【发布时间】:2021-01-15 03:27:17
【问题描述】:

我有一个包含 Registrationdate 列的 CSV 文件。格式为月/日/年。我正在尝试读取此 CSV 并将数据插入数据库。但它显示了一个日期格式错误。我知道 SQL 将数据格式作为年-日-月。但是我需要一种方法在将整列插入数据库之前将其转换为这种格式。请告诉我一种将格式从 mm/dd/y 转换为 y-mm-dd 的方法。

import csv

with open('STUDENTDATA.csv',newline='',encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
next(reader, None)

for row in reader:
    sql = "INSERT INTO STUDENTDETAILS (studentid, firstname, lastname, registrationdate, class, section) VALUES ('%s','%s','%s','%s','%s','%s')" % (row[0],row[1],row[2],row[3],row[4],row[5])
    
    try:
        cursor = mydb.cursor()
        cursor.execute(sql)
        print("Value inserted!")
        mydb.commit()
    except Exception as e:
        print(str(e))



1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1
1292 (22007): Incorrect date value: '1/13/2021' for column 'REGISTRATIONDATE' 
at row 1

【问题讨论】:

    标签: python csv simpledateformat mysql-date


    【解决方案1】:

    您的日期格式错误。您的日期格式是“D/MM/YYYY”,它应该是“YYYY-MM-DD”的形式。

    *如果您提供数据集中的一些数据会更清楚。

    或者尝试转换日期格式并告诉我它是否有效

    #编辑

    以下是我们如何将日期转换为“YYYY-MM-DD”

    data=[]                          #contains all the data from your dataset
    formated_date=[]                 #contains formated date in the form of "YYYY-MM-DD"
    
    with open('STUDENTDATA.csv',newline='',encoding='utf-8') as csvfile:     #reading the csv file
        reader = csv.reader(csvfile)
        next(reader, None)
        for row in reader:
            data.append(row)
    
    for i in data:
        a=i[3].split('/')
        newform=f'{a[2]}-{a[0]}-{a[1]}'         #changing the date format
        formated_date.append(newform)           #and saving it to another list
    

    我们在这里所做的是将数据集中的所有数据收集到一个列表中,即。 'data',我们解析出包含日期的部分并用'/'分割,然后我们附加一个新列表,即'formated_date',其中包含sql接受的日期格式的格式化日期。

    现在我们需要将代码用sql连接起来,保存到数据库中。

    #这是最终代码

    import csv
    import mysql.connector
    
    mydb=mysql.connector.connect(host='localhost',user='*******',passwd='*****',database='STUDENTDATA')
    cursor=mydb.cursor()
    
    data=[]                          #contains all the data from your dataset
    formated_date=[]                 #contains formated date in the form of "YYYY-MM-DD"
    
    with open('STUDENTDATA.csv',newline='',encoding='utf-8') as csvfile:     #reading the csv file
        reader = csv.reader(csvfile)
        next(reader, None)
        for row in reader:
            data.append(row)
    
    for i in data:
        a=i[3].split('/')
        newform=f'{a[2]}-{a[0]}-{a[1]}'         #changing the dateformat
        formated_date.append(newform)           #and saving it to another list
    
    for i in range(len(data)):
        sql="INSERT INTO STUDENTDETAILS (studentid, firstname, lastname, registrationdate, class, section) VALUES ('%s','%s','%s','%s','%s','%s')" % (data[i][0],data[i][1],data[i][2],formated_date[i],data[i][4],data[i][5])
        try:
            cursor = mydb.cursor()             #saving the file into the database
            cursor.execute(sql)
            print("Value inserted!")
            mydb.commit()
        except Exception as e:
            print(str(e)) 
    

    希望它有所帮助。如果有任何问题,请务必告诉我。

    【讨论】:

    • 学生名姓氏注册日期班级第 101 节 RATIK SONDKAR 1/13/2021 CS A 102 RAJDEEP KARPE 1/13/2021 CS A 103 AKSHAY JAGTAP 1/13/2021 CS A 104 SHUNHAM YAMGAR 1/13 /2021 CS A 105 SHUBHAM YADAV 1/13/2021 CS A 106 AKSHAY MANKAR 1/13/2021 CS A 107 MOHIT NIKAM 1/13/2021 CS A 108 OMKAR DESHPANDE 1/13/2021 CS A 109 DEEPAK KHAPRE 1/13 /2021 CS A
    • 对不起格式。这是数据..我知道格式错误。我正在寻求通过 python 中的代码更改格式的方法。
    • 立即查看@Pratik Sondkar
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2014-09-29
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多