两个日期之间的计算差异MySQL/Python

2024-10-01 07:13:55 发布

您现在位置:Python中文网/ 问答频道 /正文

两个日期之间的差异存储在MySQL中。在

运行以下代码:

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'

result/result2的格式为(datetime.datetime(2017, 1, 27, 22, 25, 39),)。在

我想我在tuple/string格式上做错了什么。感谢任何帮助!在


Tags: importeventexecutedatetimetimetypeconnectioncursor
2条回答

看起来cursor.fetchone()返回以字段元组形式表示的记录。 在您的例子中,只有一个字段(Timewhen),因此您有一个包含一个元素的元组。在

这样,要获得实际值,您需要从元组中提取这个元素,这样diff = result2[0] - result[0]应该可以工作。在

resultresult2是元组,表示从查询返回的整行。在本例中,它们包含一个元素,因为您的查询只包含一列。您可以使用[]运算符提取此值。E、 g.:

result=cursor.fetchone()[0]

相关问题 更多 >