将列值转换为datetime以插入AccessDB

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

我试图将Pandas Dataframe的值填充到MS Access表中。我使用以下Pandas内置的DF.iterrows()迭代DataFrame的每一行,并将每一行插入Access表。

for index,row in df.iterrows():
    print(repr(row['Vote_date'])) #Using iterrows() temporarily converts datetime64[ns] values into Timestamps  
    row['Vote_date'] = row['Vote_date'].to_pydatetime() #This converts all values in this column, except NaT values.

    cursor.execute("INSERT INTO Vote(vote_date) VALUES(?)", row['Vote_date'])  

当我运行此代码时,我收到以下错误:

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

Pandas Timestamps值无法插入MS Access表。研究表明,我需要将列值转换为Python datetime值,以便插入Access DB。

是否有另一种迭代方法可以用来成功地将Python datetime值插入MS Access?还处理NaT值?

python python-3.x pandas numpy ms-access-2016
2个回答
0
投票

您是否考虑过将其转换为日期时间然后运行循环? https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_pydatetime.html

df['Vote_date'] = df['Vote_date'].dt.to_pydatetime()
df.loc[df['Vote_date'].isnull(),"Vote_date"] = None
for index,row in df.iterrows():
    cursor.execute("INSERT INTO Vote(vote_date) VALUES(?)", row['Vote_date'])  

0
投票

我有运气这样做:

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。

pandas where docs

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