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

我有一段代码在Python中读取一个Excel文件并保存到红移数据库。

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] (自定义格式)。

如何正确地获取数据库中的这些date时间值?

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

从xlrd上的文档

要读取date值,可以使用xldate_as_tuple函数

因为date以excel文件格式存储为数字

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

 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数据执行插入操作更快,