Postgres视图中的变量?

时间:2017-08-17 12:28:52

标签: python postgresql

我在Postgres中有一个查看主表(1.5亿行)并从前一天检索数据的视图(昨天返回SELECT的函数;这是让视图遵守我的分区约束的唯一方法)和然后将它与两个维度表连接起来。这工作正常,但我如何在Python中循环这个查询?有没有办法让日期变得动态?

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 个答案:

答案 0 :(得分:1)

要在for循环的间隔内逐日循环,您可以执行以下操作:

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