[英]looping through a week of dates in Python postrgres query string and add those results to the csv datframe list
[英]Loop through list of dates in Python query string
我正在嘗試使用Pandas和SQLAlchemy在MySQL實例上運行查詢。 在實際查詢中,有一個“ WHERE”語句引用一個特定的日期。 我想針對Python列表中的每個日期分別運行此查詢,並將每個日期的數據框迭代地附加到另一個主數據框。 我的代碼現在看起來像這樣(不包括創建SQLAlchemy引擎):
dates = ['2016-01-12','2016-01-13','2016-01-14']
for day in dates:
query="""SELECT * from schema.table WHERE date = '%s' """
df = pd.read_sql_query(query,engine)
frame.append(df)
我的錯誤是
/opt/rh/python27/root/usr/lib64/python2.7/site-packages/MySQLdb/cursors.pyc in execute(self, query, args)
157 query = query.encode(charset)
158 if args is not None:
--> 159 query = query % db.literal(args)
160 try:
161 r = self._query(query)
TypeError: not enough arguments for format string
我想知道將列表中的字符串插入查詢字符串的最佳方法是什么?
使用params
來參數化您的查詢 :
dates = ['2016-01-12', '2016-01-13', '2016-01-14']
query = """SELECT * from schema.table WHERE date = %s"""
for day in dates:
df = pd.read_sql_query(query, engine, params=(day, ))
frame.append(df)
請注意,我刪除了%s
占位符周圍的引號-數據類型轉換將由數據庫驅動程序本身處理。 如果需要的話,它會暗含引號。
而且,您可以在循環之前定義一次查詢-無需在內部進行查詢。
我也認為您可能需要一個date
或datetime
對象列表,而不是字符串:
from datetime import date
dates = [
date(year=2016, month=1, day=12),
date(year=2016, month=1, day=13),
date(year=2016, month=1, day=14),
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.