将日期正确插入 SQL [英] Inserting date correctly into SQL
问题描述
我有这样的 Python 代码:
I have Python code like this:
with open('task9_in.csv', 'r') as file:
reader = csv.reader(file, delimiter = ',')
for row in reader:
all_data.append(row)
csv文件中的数据结构是这样的:
The data structure in the csv file is like this:
test1 1/6/2019 1243 login
但是当我运行代码时,数据是这样插入到数据库中的:
However when I run the code, the data is inserted into the database like this:
test1 2019/6/1 1243 login
0
没有被填充.我希望预期日期为
The 0
is not being padded in. I want the expected date as
test1 2019/06/01 1243 login
如何用0
插入数据库.
这是表定义:
推荐答案
鉴于 CSV 文件如下所示:
Given that the CSV file looks like this:
test1, 1/6/2019, 1243, login
您的 CSV 文件本身缺少日期填充.因此,您可以使用 datetime 库从您的行中隐藏日期字符串.
You are missing the padding for date in your CSV file itself. So, you can covert the date string from your row using datetime library.
这个库足够灵活,可以支持多种格式.更多信息在这里(https://thispointer.com/python-how-to-convert-datetime-object-to-string-using-datetime-strftime/)
This library is flexible enough to support multiple formatting. More info here (https://thispointer.com/python-how-to-convert-datetime-object-to-string-using-datetime-strftime/)
试试这个:
import datetime
before_string = '1/6/2019'
date = list(map(int, before_string.split('/'))
date_obj = datetime.date(date[2], date[1], date[0])
padded_string = date_obj.strftime('%d/%m/%Y')
print(padded_string)
输出:
01/06/2019
现在可以将其插入到您的 SQL 表中.
Now this can then be inserted into your SQL table.
这篇关于将日期正确插入 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!