2017-01-27 211 views
2

我想獲得兩個日期之間的時間差Python 2.7,其中日期存儲和檢索從MySQL兩個日期之間的計算差異MySQL/Python

運行以下代碼:

import datetime 
import time 
from time import sleep 
import MySQLdb as mdb 

connection = mdb.connect('localhost', 'root', 'pwd', 'mydatabase'); 
cursor = connection.cursor() 

TimeFormat = '%Y-%m-%d %H:%M:%S' 

#Insert times and type of event into database 
with connection: 
    #First event 
    Now=datetime.datetime.now() 
    Timewhen1=Now.strftime(TimeFormat) 
    print "Start time", Timewhen1 
    Type="1" 
    cursor.execute('INSERT INTO LogEvent (Timewhen, Type) VALUES (%s, %s)',(Timewhen1,Type)) 
    sleep(1) #Real time will be unknown, seconds to days 

    #Second event 
    Now=datetime.datetime.now() 
    Timewhen2=Now.strftime(TimeFormat) 
    print "Stop time", Timewhen2 
    Type="0" 
    cursor.execute('INSERT INTO LogEvent (Timewhen, Type) VALUES (%s, %s)',(Timewhen2,Type)) 

#Get time difference 
with connection: 
    cursor.execute("SELECT Timewhen FROM LogEvent ORDER BY ID DESC LIMIT 0,1") 
    result=cursor.fetchone() 

    cursor.execute("SELECT Timewhen FROM LogEvent ORDER BY ID DESC LIMIT 1,1") 
    result2=cursor.fetchone() 

diff=result2-result 
print "Diff", diff 

得到了以下結果:

TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

結果/ RESULT2是在(datetime.datetime(2017, 1, 27, 22, 25, 39),)格式。

猜猜我做錯了元組/字符串格式。任何幫助表示讚賞!

回答

1

它看起來像cursor.fetchone()返回作爲字段的元組呈現的記錄。 就你而言,你只有一個字段(Timewhen),所以你有一個元素的元組。

這樣,爲了得到實際的值,你需要從元組中提取這個元素,所以diff = result2[0] - result[0]應該工作。

0

resultresult2是表示從查詢返回的整行的元組。在這種情況下,它們包含一個元素,因爲您的查詢只包含一列。您可以使用[]運算符來提取此值。例如:

result=cursor.fetchone()[0] 
相關問題