【问题标题】:How to use date range in python to pull /query data in mySQL如何在 python 中使用日期范围在 mySQL 中提取/查询数据
【发布时间】:2012-09-14 01:44:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: python mysql database date


    【解决方案1】:

    datetime 类与strftime 函数一起使用。

    datetime 类用于构建表示特定日期和时间的对象。 strftime 函数根据您选择的格式将其转换为特定的字符串。

    根据MySQL's documentation,标准日期时间格式为YYYY-MM-DD HH:MM:SS

    这是一个应该可以工作的例子:

    day1 = datetime.datetime(2012, 1, 1).strftime('%Y-%m-%d %H:%M:%S')
    day2 = datetime.datetime(2012, 1, 2).strftime('%Y-%m-%d %H:%M:%S')
    con.execute("select * from table where date >= %s and date < %s", (day1, day2))
    

    如果您想进行其他查询,只需在循环的每一轮中创建适当的 datetime.datetime 对象即可。例如:

    for i in xrange(1, 10):
        # ...
        day2 = datetime.datetime(2012, 1, i).strftime('%Y-%m-%d %H:%M:%S')
        # ...
    

    【讨论】:

      【解决方案2】:

      使用datetime.date 对象。它们是很棒的东西,因为有了它们你可以:

      • 今天轻松计算 (dt.date.today()),
      • 第二天轻松计算 (start + dt.timedelta(days = 1),
      • 比较日期(例如start &lt; end
      • 将它们直接输入con.execute。没有 需要将它们预先格式化为字符串。

      import datetime as dt
      start = dt.date(2012,1,1)
      end = dt.date.today()
      
      while start < end:
          nextday = start + dt.timedelta(days = 1)
          con.execute("select * from table where date >= %s and date < %s",
                      (start, nextday))
      
          start = nextday
      

      【讨论】:

      • 删除逗号,并在con.execute 行中添加一个百分号%,因为现有代码没有正确构建sql
      • 我正在使用con.execute 的2-参数形式。见PEP 249。这是为参数化 SQL 语句提供参数的正确方法。这是使用con.execute 的首选方式,因为它可以保护您免受sql injection attacks 的侵害。
      【解决方案3】:

      你需要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
      

      重要通知:我更新了答案以解决一个严重问题。永远不要永远使用字符串格式(a.k.a.%)来构建 SQL 查询,因为它可能会引发严重的问题,包括 SQL 注入。使用Python-&lt;db_driver&gt; api,其中几乎所有 RDMBes 都提供相同的语法

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

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

      【讨论】:

      • 实际上,我收到语法错误“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在 '%s 和 date
      • 发现我必须将“%s”改为“?”这个查询将起作用。基于stackoverflow.com/questions/9603616/…
      • start = datetime.date(2012,01,01) 给出 SyntaxError: invalid token 错误。应该是start = datetime.date(2012,1,1)
      猜你喜欢
      • 1970-01-01
      • 2019-02-10
      • 2022-01-03
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2011-01-01
      相关资源
      最近更新 更多