![](/img/trans.png)
[英]Unable to save the correct file format to S3 using Databricks (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()
要讀取日期值,可以使用xldate_as_tuple函數
因為日期在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數據執行插入操作更快,更容易,並且通常建議這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.