【问题标题】:Pandas to_sql using wrong data type, can it be changed?Pandas to_sql 使用错误的数据类型,可以更改吗?
【发布时间】:2021-09-27 23:37:26
【问题描述】:

我已将一些 SQL Server 数据加载到 Pandas 数据框中。这里发生了一些转变。完成后,我尝试使用 SQLAlchemy to_sql 函数将 Dataframe 转储回 SQL。目标表由 SQLAlchemy 自动创建。

但是,我收到此错误消息...

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

这是因为 Dataframe 包含许多日期字段。这些日期字段中的某些数据设置为“0001-01-01”,这显然不适合 DATETIME 数据类型,但适合 DATETIME2 数据类型。

有没有办法强制使用 DATETIME2 而不是 DATETIME?

【问题讨论】:

    标签: python pandas dataframe sqlalchemy


    【解决方案1】:

    您可以将DATETIME2指定为dtype,如下所示。

    df.to_sql(
      'Temp',
      target_engine,
      schema = 'dbo',
      if_exists = 'replace',
      chunksize = 250000,
      index = False,
      dtype={"CreatedDate": DATETIME2}
    )
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 2019-02-16
      • 1970-01-01
      • 2020-07-24
      • 2019-12-21
      • 2011-06-20
      • 2022-01-12
      • 2015-03-02
      • 1970-01-01
      相关资源
      最近更新 更多