1

I'm writing a python script that hits an API and then writes various data to a MySQL database.

One of the fields I'm trying to write is a date object, but I keep running into a "TypeError: 'datetime.datetime' object is not iterable" error and can't seem to get past it. I'm convinced it's something really simple, but I can't figure out what.

First, I call the API to get a json object with several dates and metrics in them. Then I loop through the dates and am trying to write them to the DB.

for day in results:

   mydate = datetime.datetime.strptime(day['date'], '%Y-%m-%d')

   print mydate

   date_query = "INSERT INTO sendgrid_stats (date) VALUES (%s)"

   cursor.execute(date_query, mydate)
   connection.commit()

If you print the date that's attempted to be inserted, it looks like "2015-07-26 00:00:00" (without the quotes).

Does anyone know what I'm doing wrong? My face hurts from banging my head into the keyboard.

3
  • What is the traceback? which line is the error on? Commented Jul 31, 2015 at 15:46
  • Traceback (most recent call last): File "getdailystats.py", line 25, in <module> cursor.execute(date_query, mydate) File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 187, in execute query = query % tuple([db.literal(item) for item in args]) TypeError: 'datetime.datetime' object is not iterable Commented Jul 31, 2015 at 15:47
  • I have the exact same problem but it's not solved by a query change. It's just raw data from a file. Any ideas how to solve that? Commented Jul 17, 2021 at 20:06

1 Answer 1

5

You need to pass query parameters as an iterable. Make it a tuple, for instance:

cursor.execute(date_query, (mydate, ))
Sign up to request clarification or add additional context in comments.

1 Comment

That was it! Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.