python - 如何将 Pandas NaT 日期时间值正确插入到我的 postgresql 表中

标签 python pandas postgresql sqlalchemy psycopg2

我想将数据帧批量插入到我的 postgres dB 中。我的数据框中的某些列是带有 NaT 的日期类型作为空值。 PostgreSQL 不支持,我尝试替换 NaT (使用 Pandas )与其他 NULL 类型标识,但在我的插入过程中不起作用。
我用过 df = df.where(pd.notnull(df), 'None')替换所有 NaT s,由于数据类型问题而不断出现的错误示例。

Error: invalid input syntax for type date: "None"
LINE 1: ...0,1.68757,'2022-11-30T00:29:59.679000'::timestamp,'None','20...
我的驱动程序和对 postgresql dB 的插入语句:
def execute_values(conn, df, table):
    """
    Using psycopg2.extras.execute_values() to insert the dataframe
    """
    # Create a list of tupples from the dataframe values
    tuples = [tuple(x) for x in df.to_numpy()]
    # Comma-separated dataframe columns
    cols = ','.join(list(df.columns))
    # SQL quert to execute
    query  = "INSERT INTO %s(%s) VALUES %%s" % (table, cols)
    cursor = conn.cursor()
    try:
        extras.execute_values(cursor, query, tuples)
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print("Error: %s" % error)
        conn.rollback()
        cursor.close()
        return 1
    print("execute_values() done")
    cursor.close()
关于我的数据框的信息:对于这种情况,罪魁祸首仅是日期时间列。
enter image description here
这通常是如何解决的?

最佳答案

你在重新发明轮子。只需使用 Pandas 的 to_sql方法,它会

  • 匹配列名,和
  • 照顾好 NaT值。

  • 使用 method="multi"为您提供与 psycopg2 相同的效果 execute_values .
    from pprint import pprint
    
    import pandas as pd
    import sqlalchemy as sa
    
    table_name = "so64435497"
    engine = sa.create_engine("mssql+pyodbc://@mssqlLocal64", echo=False)
    with engine.begin() as conn:
        # set up test environment
        conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
        conn.execute(
            sa.text(
                f"CREATE TABLE {table_name} ("
                "id int identity primary key, "
                "txt nvarchar(50), "
                "txt2 nvarchar(50), dt datetime2)"
            )
        )
        df = pd.read_csv(r"C:\Users\Gord\Desktop\so64435497.csv")
        df["dt"] = pd.to_datetime(df["dt"])
        print(df)
        """console output:
                           dt  txt2  txt
        0 2020-01-01 00:00:00  foo2  foo
        1                 NaT  bar2  bar
        2 2020-01-02 03:04:05  baz2  baz
        """
    
        # run test
        df.to_sql(
            table_name, conn, index=False, if_exists="append", method="multi"
        )
        pprint(
            conn.execute(
                sa.text(f"SELECT id, txt, txt2, dt FROM {table_name}")
            ).fetchall()
        )
        """console output:
        [(1, 'foo', 'foo2', datetime.datetime(2020, 1, 1, 0, 0)),
         (2, 'baz', 'baz2', None),
         (3, 'bar', 'bar2', datetime.datetime(2020, 1, 2, 3, 4, 5))]
        """
    

    关于python - 如何将 Pandas NaT 日期时间值正确插入到我的 postgresql 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64435497/

    相关文章:

    Python 符号或操作 "**"

    pandas - Python pandas 如何获取 groupby 的逆向

    python - 用于删除跨列具有相同内容的连续重复行的数据框

    postgresql - 数据库/sql Exec()函数失败,并置字符串

    javascript - 在 Sequelize JS 中禁用主键

    database - 了解 Heroku 中的多个数据库

    python - 如何将一个DataFrame分成两个小的

    python - 无法将非有限值(NA 或 inf)转换为整数

    python - pyplot 图表上光标位置的详细日期

    python - 具有平均时间的 Pandas 数据透视表