I'm trying to format a mysql statement with today's data, as well as 7 days back. I'm pretty sure the date is in the correct format, so I don't think that's the issue.
The error report is:
Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
result = self._query(query)
Traceback (most recent call last):
AttributeError: 'int' object has no attribute 'format'
e.g.
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))
cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)
解决方案
Using prepared statements (safe way):
qry = """
SELECT *
FROM db
WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" #
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d')) # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string
cursor.execute(qry, [today, week_ago])
Using .format() which leaves you at risk for sql injections (if you pass user input to .format() e.g.)
qry = """
SELECT *
FROM db
WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d')) # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string
qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)