使用Python从MySQL数据库中提取两个日期时间之间的数据

使用Python从MySQL数据库中提取两个日期时间之间的数据,python,mysql,datetime,Python,Mysql,Datetime,我试图找出如何从一个表中提取数据,该表有一个名为“sent_time”的列,datetime介于两个datetime之间。正如您在代码中看到的,格式为“YYYY-dd-MM HH:MM:ss”。根据我对代码的更改方式,我会不断收到不同的错误。你能告诉我哪里出了问题吗 我想给你我所有其他文件的所有信息,以及我的拍摄目的,看看你是否可以复制并真正让它工作,看看它是否不仅仅是我的系统或我的一些配置 我有一个带有一个表的数据库。我们称它为“table1”。该表按如下列进行分解: 发送时间|发送时间| i

我试图找出如何从一个表中提取数据,该表有一个名为“sent_time”的列,datetime介于两个datetime之间。正如您在代码中看到的,格式为“YYYY-dd-MM HH:MM:ss”。根据我对代码的更改方式,我会不断收到不同的错误。你能告诉我哪里出了问题吗

我想给你我所有其他文件的所有信息,以及我的拍摄目的,看看你是否可以复制并真正让它工作,看看它是否不仅仅是我的系统或我的一些配置

我有一个带有一个表的数据库。我们称它为“table1”。该表按如下列进行分解:

发送时间|发送时间| id1 |激活id2 |激活id3 |未激活id1 |未激活id2 |未激活id3 |未激活位置|激活位置|未激活..更多

假设这是两个或两个以上的客户相互之间传递商品。每个客户都有三个id

我创建了一个“config.ini”文件,让我的生活更轻松

[mysql]
host = localhost
database = db_name
user = root
password = blahblah
我创建了一个“python\u mysql\u dbconfig.py”

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
现在这是我一直在研究的代码,它应该用来提取两个日期时间之间的行。但我一直在犯这样的错误:

   **Traceback (most recent call last):
  File "C:\Python34\timerange.py", line 33, in <module>
    dt_start = datetime.strptime(userIn,timeShape)
TypeError: must be str, not tuple**

我在输入中使用了dateutil.parser.parse,并且能够得到一些结果……我有一个新的错误,但我将在下面的问题中发布它。谢谢您的帮助。

尝试在查询字符串中引用日期时间%s:start\u date=datetime.datetime(userIn,timeShape)中的第27行“C:\Python34\timerange.py”文件AttributeError:type对象“datetime.datetime”没有属性“datetime”,我更改了第27行和第28行以反映“datetime(userIn,timeShape)”和“datetime(userEnd,timeShape)”,现在给我这个错误回溯(最近一次调用):文件“C:\Python34\timerange.py”,第27行,在start\u date=datetime('2015-09-12 13:12'11'中#(userIn,timeShape)TypeError:需要一个整数(Get type str)
# 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 ("")