导入的数据显示了regulator格式

时间:2019-02-19 19:02:34

标签: python mysql

在MySQL中从Excel导入的数据(仅日期和执行时间dd.mm.yyyy)显示为0000-00-00。我试图将这些列的dtypes更改为datetime(通过使用pd.to_datetime()),然后将其导出到Excel中。

df['columnName'] = pd.to_datetime(df['columnName'])

它没有帮助。通常,我正在尝试将数据从Excel导入MySQL。

query = """
INSERT INTO sanction (
    id,
    organization_type, organization, date,
    decision_number, penalty_type, penalty_way,
    penalty, violation, execution_period,
    article, note, type_npa,
    department, uploaded_date)
VALUES (
    null,
    %s, %s, %s,
    %s, %s, %s,
    %s, %s, %s,
    %s, %s, %s,
    %s, %s)
"""

for r in range(1, sheet.nrows):
    organization_type = sheet.cell(r, 1).value
    organization = sheet.cell(r, 2).value
    date = sheet.cell(r, 3).value
    decision_number = sheet.cell(r, 4).value
    penalty_type = sheet.cell(r, 5).value
    penalty_way = sheet.cell(r, 6).value
    penalty = sheet.cell(r, 7).value
    violation = sheet.cell(r, 8).value
    execution_period = sheet.cell(r, 9).value
    article = sheet.cell(r, 10).value
    note = sheet.cell(r, 11).value
    type_npa = sheet.cell(r, 12).value
    department = sheet.cell(r, 13).value
    uploaded_date = datetime.now().strftime("%Y-%m-%d %H:%M")

values = (
    # the first value of the INSERT statement will be NULL
    organization_type, organization, date,              # 3 elements
    decision_number, penalty_type, penalty_way,         # 3 elements
    penalty, violation, execution_period,               # 3 elements
    article, note, type_npa,                            # 3 elements
    department, uploaded_date,                          # 2 elements
)
mycursor.execute(query, values)

1 个答案:

答案 0 :(得分:0)

插入数据中的'0000-00-00'值表示MySQL无法将您传递的值转换为日期。

当将字符串转换为date datatype时,MySQL基本上采用yyyy-mm-dd格式(对于yyyy-mm-dd hh24:mi:ss则采用datetime格式),并具有一定的灵活性。它无法识别您的输入格式(dd.mm.yyyy)。从文档中:

  

无效的DATEDATETIMETIMESTAMP值将转换为适当类型('0000-00-00''0000-00-00 00:00:00')的“零”值。 / p>

一种解决方案是使用the STR_TO_DATE() function在查询中进行显式转换,例如:

INSERT INTO sanction (
    id,
    organization_type, organization, date,
    decision_number, penalty_type, penalty_way,
    penalty, violation, execution_period,
    article, note, type_npa,
    department, uploaded_date)
VALUES (
    null,
    %s, %s, STR_TO_DATE(%s, '%d.%m.%Y'),
    %s, %s, %s,
    %s, %s, %s,
    %s, %s, %s,
    %s, %s)