如何使用 python date 按天提取 mySQL 中的数据?
假设我想要 day1
和 day2
(或 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/