如何获得python中两个日期变量之间的小时差异
我正在使用python 2.7.2。我试图得到两个日期变量之间的差异,这是由MySQL查询导致的。如何获得python中两个日期变量之间的小时差异
#!/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
,并获得的第一要素:如果差值可超过1天,你应该使用`
inv = cursor.fetchone()[0]
remote_inv = cursor.fetchone()[0]
diff = remote_inv - inv
diff_minutes = diff.total_seconds()/60
啊..这就是这个伎俩......感谢帮助我...... – 2014-11-21 10:20:56
strftime
?
例如:
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
我尝试使用strftime但它说“AttributeError:'元组'对象没有属性'strftime'”...在这里我导入日期时间,但它仍然不是工作...... – 2014-11-21 10:22:32
diff.total_seconds()'。我不明白格式是如何获得小时 – 2014-11-21 09:39:48