2017-08-17 39 views
0

我在Postgres中查看一個主表(1.5億行),並從前一天獲取數據(一個返回SELECT的函數;它是讓視圖尊重我的分區約束的唯一方法),然後將它與兩個維度表連接起來。這工作正常,但我將如何在Python中循環查詢?有沒有辦法使日期動態?Postgres視圖中的變量?

for date in date_range('2016-06-01', '2017-07-31'): 
    (query from the view, replacing the date with the date in the loop) 

我的解決方法是從字面上複製和粘貼作爲一個巨大的select語句格式字符串中的整個視圖,然後通過在一個循環的日期。這很有效,但似乎必須有更好的解決方案來利用現有視圖或傳入一個未來可能有用的變量。

回答

1

要循環利用一天的時間間隔內一天一個循環,你可以這樣做:

import datetime 

initialDate = datetime.datetime(2016, 6, 1) 
finalDate = datetime.datetime(2017, 7, 31) 

for day in range((finalDate - initialDate).days + 1): 
    current = (initialDate + datetime.timedelta(days = day)).date() 
    print("query from the view, replacing the date with " + current.strftime('%m/%d/%Y')) 

與調用查詢更換打印。如果日期是字符串,你可以做這樣的事情:

initialDate = datetime.datetime.strptime("06/01/2016", '%m/%d/%Y') 
+0

嗨,對不起,我的意思是如何編輯一個視圖在Postgres中是動態的。我有一個我想在Python循環中查詢的視圖,所以我從該視圖中選擇日期等於我的循環中的日期。 – trench

+0

如果您可以更新您的問題以包含視圖代碼和返回類型期待它,也許我可以幫助你。 –