以编程方式在python sql字符串中输入日期

时间:2015-06-12 10:50:27

标签: python sql django postgresql

这是我当前的查询

cursor = connection.cursor()
cursor.execute('SELECT *'\
    'FROM students' \
    'WHERE numberofclasses > 4')
list = cursor.fetchall()

现在我想添加到字符串:

  1. registrationdate过去一个月 - >如何计算并将结果添加到字符串
  2. 这个名字以' l'开头。 - >如何将name like '%l'添加到上面的字符串
  3. 注意:

    1. 对于我的问题,保留'...'\ '...'\的字符串格式而不是在''' ... '''之间写入
    2. 这一点非常重要
    3. 这是一个非常复杂的查询的示例,必须以这种方式执行,而不是通过Django ORM平台执行。

1 个答案:

答案 0 :(得分:0)

让我们在几个问题上分手:

  1. 如何确定'过去一个月' python date of the previous month
  2. 数据库的格式取决于您使用的后端 Mysql:https://dev.mysql.com/doc/refman/5.1/en/date-and-time-literals.html Postgres:http://www.postgresql.org/docs/9.1/static/datatype-datetime.html
  3. 在字符串中输入值:
  4. 您可以连接格式化日期:

    cursor.execute('SELECT *'\
        'FROM students' \
        'WHERE numberofclasses > 4' \
        'AND mydate > \'%s\'', [month_ago.isoformat()])
    

    https://docs.python.org/2/library/datetime.html#datetime.date.isoformat

    我不明白你的第二个问题,因为这似乎已经包含了答案。