【问题标题】:How to insert a date time column from excel into datetime field in mySQL?如何将excel中的日期时间列插入mySQL中的日期时间字段?
【发布时间】:2017-12-31 21:38:52
【问题描述】:

我编写了一个 python 脚本来将数据从 excel 电子表格导入 mysql 数据库。但 Excel 电子表格中的两列采用以下自定义格式:YYYY-MM-DD HH:MM:SS。并且 mysql 表具有datetime 格式的这些列。但是,当我运行脚本时,我收到错误,即无法将此格式添加到 SQL 中的日期时间格式。

下面是我的python脚本:

query = """INSERT INTO table (col1, col2, col3, col4, col5) VALUES (%s, %s, %s, %s, %s)"""
    for r in range(1, sheet.nrows):
        col1 = sheet.cell(r,0).value
        col2 = sheet.cell(r,1).value
        col3 = sheet.cell(r,2).value
        col4 = sheet.cell(r,3).value

        col5       = sheet.cell(r,4).value
        #col5 = xlrd.xldate.xldate_as_datetime(sheet.cell(r,4).value, book.datemode)

        # Assign values from each row
        values = (col1, col2, col3, col4, col5)

        # Execute sql Query
        cursor.execute(query, values)

    # Close the cursor
    cursor.close()

    # Commit the transaction
    con.commit()

谁能告诉我如何将excel中的日期时间列插入到mySQL的日期时间字段中??

【问题讨论】:

    标签: python mysql excel date datetime


    【解决方案1】:

    也许你已经解决了这个问题。但是如果你还没有解决,请试试这个:

    import xlrd, datetime
    ...
    
    col5 = datetime.datetime(*xlrd.xldate_as_tuple(sheet.cell(r,4).value, book.datemode))
    

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多