title: Using Python to pull data from MySQL database that fall between two datetimes
body: <p>I am trying to figure out how to pull data from a table that has a column that is called 'sent_time' and the datetime falls between two datetimes. The format, as you can see in the code, is 'YYYY-dd-MM HH:mm:ss' . I keep getting different errors depending on how I change the code. Could you please tell me where I'm going wrong?</p>
  
  <p>I want to give you all the information I have with all the other files and what I'm shooting for to see if you can replicate and actually get it working just to see if it's not just my system or some configuration I have..</p>
  
  <p>I have a database with one table.Lets call it ‘table1’ The table is broken down with columns like this:</p>
  
  <p>sent_time | delivered_time |id1_active |id2_active |id3_active |id1_inactive |id2_inactive |id3_inactive |location_active |location_inactive …..`lots more</p>
  
  <p>Lets say that these are two or more customers delivering goods to and from each other. Each customer has three id#s.</p>
  
  <p>I created a ‘config.ini’ file to make my life a bit easier</p>
  
  <pre><code>[mysql]
  host = localhost
  database = db_name
  user = root
  password = blahblah
  </code></pre>
  
  <p>I created a ‘python_mysql_dbconfig.py’</p>
  
  <pre><code>from configparser import ConfigParser
  
  def read_db_config(filename=’config.ini’, section=’mysql’):
  “”” Read database configuration file and return a dictionary object
  :param filename: name of the configuration file
  :param section: section of database configuration
  :return: a dictionary of database parameters
  “””
  # create parser and read ini configuration file
  parser = ConfigParser()
  parser.read(filename)
  
  # get section, default to mysql
  db = {}
  if parser.has_section(section):
  items = parser.items(section)
  for item in items:
  db[item[0]] = item[1]
  else:
  raise Exception(‘{0} not found in the {1} file’.format(section, filename))
  
  return db
  </code></pre>
  
  <p>And now this is the code that I've been working on that is supposed to pull the rows that fall between two datetimes. But I keep getting this error:</p>
  
  <pre><code>   **Traceback (most recent call last):
    File "C:\Python34\timerange.py", line 33, in &lt;module&gt;
      dt_start = datetime.strptime(userIn,timeShape)
  TypeError: must be str, not tuple**
  </code></pre>
  
  <p>Can you take a look at this and tell me what I'm doing wrong?</p>
  
  <p>timerange.py </p>
  
  <pre><code># Establish a MySQL connection
  from mysql.connector import MySQLConnection, Error
  from python_mysql_dbconfig import read_db_config
  db_config = read_db_config()
  conn = MySQLConnection(**db_config)
  import xlsxwriter
  from xlsxwriter.workbook import Workbook
  import datetime
  from datetime import datetime
  cursor = conn.cursor()
  
  #creates the workbook
  workbook = xlsxwriter.Workbook('imhere.xlsx')
  worksheet = workbook.add_worksheet()
  
  #formatting definitions
  bold    = workbook.add_format({'bold': True})
  date_format = workbook.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'})
  timeShape =  '%Y-%m-%d %H:%M:%S'
  
  
  
  #actual query
  userIn = [input('start date:'),0]
  userEnd = [input('end date:'),1]
  
  
  
  query = (
      "SELECT sent_time, delivered_time, customer_name, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 "
      "WHERE sent_time BETWEEN %s AND %s"
  )
  dt_start = datetime.strptime(userIn,timeShape)
  dt_end = datetime.strptime(userEnd, timeShape)
  # Execute sql Query
  cursor.execute(query, (dt_start, dt_end))
  result = cursor.fetchall()
  
  
  #sets up the header row
  worksheet.write('A1','sent_time',bold)
  worksheet.write('B1', 'delivered_time',bold)
  worksheet.write('C1', 'customer_name',bold)
  worksheet.write('D1', 'id1_active',bold)
  worksheet.write('E1', 'id2_active',bold)
  worksheet.write('F1', 'id3_active',bold)
  worksheet.write('G1', 'id1_inactive',bold)
  worksheet.write('H1', 'id2_inactive',bold)
  worksheet.write('I1', 'id3_inactive',bold)
  worksheet.write('J1', 'location_active',bold)
  worksheet.write('K1', 'location_inactive',bold)
  worksheet.autofilter('A1:K1')
  
  
  
  print("sent_time", "delivered_time", "customer_name", "id1_active", "id2_active", "id3_active", "id1_inactive", "id2_inactive", "id3_inactive", "location_active", "location_inactive")
  for row in result:
      print(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10])
  
  # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
  for r, row in enumerate(result, start=1):  #where you want to start printing results inside workbook
      for c, col in enumerate(row):
          worksheet.write_datetime(r,0,row[0], date_format)
          worksheet.write_datetime(r,1, row[1], date_format)
          worksheet.write(r,2, row[2])
          worksheet.write(r,3, row[3])
          worksheet.write(r,4, row[4])
          worksheet.write(r,5, row[5])
          worksheet.write(r,6, row[6])
          worksheet.write(r,7, row[7])
          worksheet.write(r,8, row[8])
          worksheet.write(r,9, row[9])
          worksheet.write(r,10, row[10])
  
  
  
  
  #close out everything and save
  cursor.close()
  workbook.close()
  conn.close()
  
  #print number of rows and bye-bye message
  print ("- - - - - - - - - - - - -")
  rows = len(result)
  print ("I just imported "+ str(rows) + " rows from MySQL!")
  print ("")
  print ("Good to Go!!!")
  print ("")
  </code></pre>