如何将 dtype('<M8[ns]') 类型的数据帧列作为参数传递给 pandas python 中 sql 服务器数据库的 sql 查询?

How to pass dataframe column of type dtype('<M8[ns]') as parameter to sql query of sql server database in pandas python?

我试过这个:

 query =  "SELECT * FROM GPSEventsData09 where GPSDateTime Between '%s' and '%s'"
    
 data = pd.read_sql(query, con=engine, params = [new.iloc[0]['StartDateTime'],new.iloc[0]['EndDateTime']])

但是我收到如下错误:

ProgrammingError: (pyodbc.ProgrammingError) ('The SQL contains 0 parameter markers, but 2 parameters were supplied', 'HY000') [SQL: SELECT * FROM GPSEventsData09 where GPSDateTime Between '%s' and '%s'] [parameters: (Timestamp('2020-09-01 13:26:00'), Timestamp('2020-09-01 14:26:00'))] (Background on this error at: http://sqlalche.me/e/f405)vv

您可以在 SQL 中执行此操作,但这不是您在 SQL 中执行参数的方式。我实际上建议您在 Python 中进行参数化,然后使用结果 SQL 字符串 as-is。更直接一点:

query =  "SELECT * FROM GPSEventsData09 where GPSDateTime Between 'start_date' and 'end_date'"
query = query.replace('start_date', new.iloc[0]['StartDateTime'].strftime('%m/%d/%Y %H:%M:%S'))
query = query.replace('end_date', new.iloc[0]['EndDateTime'].strftime('%m/%d/%Y %H:%M:%S'))
data = pd.read_sql(query, con=engine)