【问题标题】:In Python I have embedded SQL code with 2 sets of between dates. How to loop the python code to run multiple sets of between dates在 Python 中,我嵌入了带有 2 组日期之间的 SQL 代码。如何循环python代码以在日期之间运行多组
【发布时间】:2020-03-23 06:12:52
【问题描述】:

如果我的问题很奇怪或令人困惑,我很抱歉。在 python 中,我有一个嵌入式 SQL 查询,在数据日期之间有 2 个。我有几个日期,我想在整个月的每个“日期集之间”循环这段代码。我觉得我错过了一个可以帮助解决这个问题的包,我还没有找到一个教程来遵循这样的事情。 比如说清酒。 List of between dates 2020-02-01 AND 2020-02-05, 2020-02-02 AND 2020-02-06, 2020-02-03 AND 2020-02-07, ... all the way to ... 2020-02-28 AND 2020-03-04

到目前为止,我的情况是这样,我不知道如何为此设置一个数组。

import psybopg2
import getpass
import pandas

con = psybopg2.connect(host="blah",database="blah",user=getpass.getpass

cur.execute("""

SELECT
Address
,Create_Data
,Event_Date

FROM
table.a

WHERE
Create_Date between '2020-03-20' AND '2020-03-25' --(want to insert set of dates from the list
AND 
Event_Date between '2020-03-20' AND '2020-03-25' --(want to insert the same between date used above

""")

output = cur.fetchall ()

data = pd.DataFrame(output)

cur.close()
con.close()`

【问题讨论】:

  • 你想连接什么数据库?有许多可用于各种数据库类型的 python 包。
  • 如果你能举个例子说明你想要达到的目标会很有帮助

标签: python sql arrays date vector


【解决方案1】:

使用datetimetimedelta

from datetime import datetime

start_date = "2020-02-01"
stop_date = "2020-02-28"

start = datetime.strptime(start_date, "%Y-%m-%d")
stop = datetime.strptime(stop_date, "%Y-%m-%d")

from datetime import timedelta
while start < stop:
    first_date = start #first date for between
    second_date = start + timedelta(days=4) #second date for between
    #Use the above in sql query
    start = start + timedelta(days=1)  # increase day one by one

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2022-12-25
    • 1970-01-01
    • 2020-09-20
    • 2018-02-10
    • 1970-01-01
    • 2012-09-02
    相关资源
    最近更新 更多