无法从 excel 文件中以正确的格式读取日期时间值并使用 python 将其保存在数据库中

Unable to read date time values in the correct format from excel file and save it in a database using python

我在 python 中有一段代码从 excel 文件中读取并保存到 redshift 数据库中。

import psycopg2
def from_redshift():
    book = xlrd.open_workbook("excelfile.xlsx")
    sheet = book.sheet_by_index(0)

    con = psycopg2.connect(dbname='dbname', host='something.com', port=portnum, user='username', password='password')
    cursor=con.cursor()

    query = """INSERT INTO table_name (col1, col2, col3, start_date, update_date) 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
        start_date     = sheet.cell(r,3).value
        update_date = sheet.cell(r,4).value

        # Assign values from each row
        values = (col1, col2, col3, start_date, update_date)

        # Execute sql Query
        cursor.execute(query, values)
        print("Executed")
    # Close the cursor
    cursor.close()

代码在读取和插入数据库时​​工作正常,但我的问题是数据库中的“start_date”和“update_date”字段属于 datetime ,所以当我尝试插入时,它给我错误,这两列的值格式不正确,当我在数据库中将这两列更改为 varchar 时,它插入这些值是一些奇怪的数字,例如 23.12345(类似的东西)。

这两列中的值类似于 YYYY-MM-DD HH:MM:[SS](自定义格式)。

如何在数据库中正确获取这些日期时间值?

    # Commit the transaction
    con.commit()
    con.close()

来自documentation on xlrd

要读取日期值,您可以使用 xldate_as_tuple function

因为日期在 excel 文件格式中存储为数字

我没有测试过这个,但是用你的代码:

def from_redshift():
    book = xlrd.open_workbook("excelfile.xlsx")
    sheet = book.sheet_by_index(0)

    for r in range(1, sheet.nrows):
        start_date     = xldate_as_tuple(sheet.cell(r,3).value, book.datemode)
        start_date = datetime.datetime(*start_date)

顺便说一句,如果您的方法名称是您在做什么的任何指示。如果您将此数据加载到 AWS Redshift 中,从 CSV 文件复制总是更快、更容易,并且通常建议比从这样的 excel 数据执行插入。