比较日期时间 mysql 和烧瓶

Compare datetime mysql and flask

我正在尝试比较两个日期时间,它显示 sql 语法错误

from flask import Flask
from flask import request, jsonify
from datetime import datetime
import pymysql

app = Flask(__name__)

class Database:
    def __init__(self):
        host = "localhost"
        user = "test"
        password = "test123"
        db = "test"
        self.con = pymysql.connect(host=host, user=user, password=password, db=db, cursorclass=pymysql.cursors.DictCursor)
        self.cur = self.con.cursor()


@app.route('/getCameraTypeAndTime/<string:date1>/<string:date2>', methods=['GET'])
def getCameraTypeAndTime(date1,date2):
    start = datetime.strptime(date1, '%Y-%m-%d %H:%M:%S')
    end = datetime.strptime(date2, '%Y-%m-%d %H:%M:%S')
    db=Database()
    result1=db.cur.execute("Select camera, COUNT(*) as freq from face_log group by camera where timestamp>start and timestamp_end<end")
    return jsonify({'result': result1})


if __name__ == '__main__':
    app.run(debug=True)

sql中的格式是日期时间但不会比较

主要问题是您试图将列值与 STARTEND MySQL keywords not your start and end variables. You need to make a query with placeholders and pass your variables to it like this (according to PyMySQL documentation):

进行比较
db.cur.execute("""
    SELECT camera, COUNT(*) AS freq FROM face_log
    WHERE timestamp > %s and timestamp_end < %s
    GROUP BY camera
""", start, end)

另请注意,SQL 查询的 GROUP BY 部分必须在 WHERE 部分之后。