python - 如何在 python 中使用日期范围在 mySQL 中拉取/查询数据

标签 python mysql database date

如何使用 python date 按天提取 mySQL 中的数据? 假设我想要 day1day2(或 day1 之后的一天)迭代 n

所以我需要“where”SQL 语句中的日期在每次迭代中看起来像下面的列表(n 次)

day1 >= '2012-01-01'  and  day2 < '2012-01-02'    ( n = 1 )
day1 >= '2012-01-02'  and  day2 < '2012-01-03'    ( n = 2 )
.
.
day1 >= yesterday    and day2  < today            ( n times ) 

.

Start_date = '2012-01-01'   <- How can I write this in python
End_date = Today()   <- and this 

这样写:

for each iteration ..
    con.execute("select * from table where date >= day1 and date < day2" )

最佳答案

您需要 datetime模块:-

import datetime
start = datetime.date(2012,01,01) 
next = start + datetime.date.resolution

while next <= datetime.date.today():
    print start, next

    con.execute("""
        select * from table where date >= %s and date < %s
    """, (start, next))

    start = next
    next = start + datetime.date.resolution

重要通知:我更新了答案以解决一个严重的问题。永远不要永远使用字符串格式(又名 % )来构建 SQL 查询,因为它会导致严重的问题,包括 SQL 注入(inject)。使用 Python-<db_driver>几乎所有 RDMBes 都提供相同语法的 api

execute("select * from blah where x=%s AND y=%s", (x, y))
                                     ^       ^  ^
                                     1       1  2

1] 没有报价,
2] 没有字符串格式

关于python - 如何在 python 中使用日期范围在 mySQL 中拉取/查询数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533854/

相关文章:

python - tkinter - wm 协议(protocol)不处理 WM_HELP 消息

python - 最长子串计算复杂度

python.h :no such file or directory error in Qtcreator

PHP5数据库密码能被盗吗?

database - 处理Paypal与本地Datasase之间的交易

python - 通过套接字发送图像并显示它

php - 如何在 Glpi 框架上创建自定义表单字段

php - 试图从数据库中回显包含多列的单行

mysql - 使用多个表中的数据更新表并按月分组 -

java - Spring批处理作业从多个来源读取