我正在使用python 2.7.2。我正在尝试获取MySQL查询导致的两个日期变量之间的小时差。
#!/usr/local/python2.7.2/bin/python
import sys
import datetime
from datetime import datetime
import MySQLdb
import MySQLdb.cursors
# Inventory db connection
db1=MySQLdb.connect(host = "localhost",user = "root",passwd ="*****",db="inventory")
cursor=db1.cursor()
cursor.execute("select max(date_created) from inventory.inventory_details;")
inv=cursor.fetchall()
# Remote Inventory db connection
db2=MySQLdb.connect(host = "remotehost",user = "root",passwd ="*****",db="inventory")
cursor=db2.cursor()
cursor.execute("select max(date_created) from inventory.inventory_details;")
remote_inv=cursor.fetchall()
print inv
print remote_inv
d1 = str(inv)
d2 = str(remote_inv)
diff = d2-d1
diff_minutes = diff.seconds/60
在这里,“ inv”的输出为((datetime.datetime(2014,11,20,13,54,7),),),remote_inv的输出为((datetime.datetime(2014,11,20,19,17,2 ),),)
我需要转换为格式“%Y-%m-%d%H:%M:%S”。我尝试使用str(),但没有帮助。
只需帮助我获得两个MySQL日期变量的差即可。我只想知道这是否可以在python中执行。
提前致谢。
这两个inv
和remote_inv
的元组的元组,你可以从你的输出看。那是因为fetchall
获取一个元组中的所有行;该元组中的每个元素本身就是所有列的元组。由于您只有一行和一列,因此您应该使用fetchone
而不是fetchall
,并获取其中的第一个元素:
inv = cursor.fetchone()[0]
remote_inv = cursor.fetchone()[0]
diff = remote_inv - inv
diff_minutes = diff.total_seconds() / 60
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句