繁体   English   中英

无法从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()

xlrd文档中

要读取日期值,可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM