将列值转换为datetime以插入AccessDB

时间:2017-12-06 23:10:22

标签: python python-3.x pandas numpy ms-access-2016

我正在尝试将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值?

2 个答案:

答案 0 :(得分:0)

您是否考虑过将其转换为日期时间然后运行循环? https://firebase.google.com/docs/firestore/solutions/counters

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'])  

答案 1 :(得分: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。

熊猫where文档