0

When I hard code a date my SQL query works fine

where_week = "dtrepor > ‘2017-04-21 07:00:00’"

but when I try to use a variable it booms out.
This variable prints to the exact same date and time but doesn’t work when substituted

my_OneWeekAgo = my_now - datetime.timedelta(days=7)
SQLdateFrom = my_OneWeekAgo.strftime("%Y-%m-%d 07:00:00")
print SQLdateFrom

2017-04-21 07:00:00

This errors out

where_week = "dtrepor > 'SQLdateFrom'"

Here is the error

An underlying database error occurred. [C:\Users\mandrews\Documents\WeeklyIncidentMaps\WeeklyVehicleTheft.gdb\MyRecords]
Failed to execute (MakeQueryTable).

1 Answer 1

2

You need to pass your variable into your string using Python Formatting.

my_OneWeekAgo = my_now - datetime.timedelta(days=7)
SQLdateFrom = my_OneWeekAgo.strftime("%Y-%m-%d 07:00:00")
print SQLdateFrom

where_week = "dtrepor > '{0}'".format(SQLdateFrom)
2
  • Thanks! I figured that out just after I posted the question. This is how I got it to work! But your version look cleaner! where_week = "dtrepor > '" + SQLdateFrom + "'" Commented Apr 28, 2017 at 21:31
  • This answer was very helpful and this website explains what passing a variable into a string is all about! digitalocean.com/community/tutorials/… Commented May 1, 2017 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.