【问题标题】:DateTime Overflow with Valid Date Access Insert具有有效日期访问插入的日期时间溢出
【发布时间】:2019-01-17 13:20:35
【问题描述】:

对于任何可以提供帮助的人,谢谢。使用 pyodbc 运行 INSERT 语句时出现一个非常奇怪的错误。错误代码是:

cursor.execute(QueryInsert,params)
pyodbc.DataError: ('22008', '[22008] [Microsoft][ODBC Microsoft Access 
Driver]Datetime field overflow  (36) (SQLExecDirectW)')

这与日期时间 1986-03-28 00:00:00 一致

我使用的代码是:

###Necessary Imports
from fredapi import Fred
import pyodbc
import datetime

###Connect to Access Database
conn = pyodbc.connect(r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" 
+r"DBQ=G:\Financial Modelling\Lease Database v1.0.accdb;")
cursor = conn.cursor()

###3M Libor
SourceCode = 'GBP3MTD156N'
fred = Fred(api_key='insert-api-key')
data = fred.get_series_all_releases(SourceCode)
A = data.shape[0]

###Cycle Through Results
for i in range(1,A):
    date1 = data.loc[i,'date']
    print(date1)
###execute query at date and only upload if empty
existquery = "SELECT * FROM EconVars WHERE SourceCode = '" + SourceCode + "' 
AND ValueDate = " + \
            "#"+str(date1.month)+"/"+str(date1.day)+"/"+str(date1.year)+"#"
cursor.execute(existquery)
existData = cursor.fetchall()

###check if empty
if len(existData) == 0:
    value1 = data.loc[i,'value']
    Description = '3M Libor'
    Source1 = 'Fred'
    params = (date1,value1,Description,Source1,SourceCode)
    QueryInsert = """INSERT into EconVars (ValueDate, ReportedValue, 
Description, Source,SourceCode)
            Values(?,?,?,?,?)"""
    cursor.execute(QueryInsert,params)
    cursor.commit()

###Commit Cursor for 3M LIBOR    
cursor.commit()
cursor.close()

我正在使用的访问文件中的表有 5 列 ValueDate 定义为日期/时间(短日期) ReportedValue 作为数字(双) 描述为短文本 源为短文本 源代码作为短文本

之前有没有人看到过这个错误或者能够复制它?

Python 3.7.2 64 位 pyodbc 4.0.25 W10 64 位和 Office 365 64 位

感谢任何有想法的人。

【问题讨论】:

  • print(repr(date1)) 是否显示datetime.datetime(1986, 3, 28, 0, 0)

标签: datetime ms-access overflow pyodbc


【解决方案1】:

我发现问题不在于 API 提供的日期时间列。

实际上,报告的值应该是双精度值,但缺失时实际上是“NaT”,我认为它是一个 numpy NULL 值或等效值。

Access 需要一个双精度值。

【讨论】:

  • 奇怪。对于数字列中的 NULL,我期望NaN,而不是NaT。不过,很好,你把它整理好了。
【解决方案2】:

这是一个示例,说明如何将您的日期时间字段更改为 OP 在对我有用的答案中所说的内容(在熊猫中):

import pandas as pd

df = pd.DataFrame(['01/01/2019',None], columns=['datetime_field'])
df['datetime_field'] = pd.to_datetime(df['datetime_field'])

df['datetime_field'] = pd.to_datetime(df['datetime_field'], errors='coerce').where(df['datetime_field'].notnull(), 0.0)

原来这个字段中的空值是NaT。

熊猫where docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多