我有一段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](自定义格式)。在
如何在数据库中正确获取这些日期时间值?在
^{pr2}$