年份超出范围Cx_Oracle Python

问题描述 投票:0回答:1

下面的代码通常给我查询数据的结果,但这次除外...

def oracle(user, pwd, dsn, sql, columns):

    # Connection to databases
    con = cx_Oracle.connect(user=user, password=pwd, dsn=dsn, encoding="UTF-8")
    cur = con.cursor()

    # Check Connection
    print('Connected')

    # Create DF
    df = pd.DataFrame(cur.execute(sql).fetchall(), columns= columns , dtype = 'str') 

    print('Shape:', df.shape)

    return df

下面是错误。

ValueError                                Traceback (most recent call last)
<timed exec> in <module>

<timed exec> in oracle_aml(user, pwd, dsn, sql)

<timed exec> in oracle(user, pwd, dsn, sql, columns)

ValueError: year -7 is out of range

问题:如何克服此警告?据说对于某些日期列,值= -7。这是由于数据库中的拼写错误。

我想添加以下表达式以忽略列类型,但并没有真正的帮助。

dtype = 'str'

感谢任何人的帮助!

python pandas cx-oracle
1个回答
0
投票

感谢this link,我已经能够解决我的问题

下面是使用的完整代码(为我工作)

import cx_Oracle
import datetime
import os
os.environ['NLS_DATE_FORMAT'] = 'YYYY-MM-DD HH24:MI:SS'


def DateTimeConverter(value):
    if value.startswith('9999'):
        return None
    return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')


def OutputHandler(cursor, name, defaulttype, length, precision, scale):
    if defaulttype == cx_Oracle.DATETIME:
        return cursor.var(cx_Oracle.STRING, arraysize=cursor.arraysize, outconverter=DateTimeConverter)


def oracle(user, pwd, dsn, sql, columns):

    # Connection to databases
    con = cx_Oracle.connect(user=user, password=pwd, dsn=dsn, encoding="UTF-8")
    con.outputtypehandler = OutputHandler

    # Cursor allows Python code to execute PostgreSQL command in a database session
    cur = con.cursor()

    # Check Connection
    print('Connected')

    # Create DF
    df = pd.DataFrame(cur.execute(sql).fetchall(), columns= columns, dtype='object')[:]

    print('Shape:', df.shape)

    return df
© www.soinside.com 2019 - 2024. All rights reserved.