【问题标题】:Calc diff between two dates MySQL/Python计算两个日期 MySQL/Python 之间的差异
【发布时间】:2017-06-13 16:34:26
【问题描述】:

我想在 Python 2.7 中获取两个日期之间的时间差,日期是在 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: 不支持的操作数类型 -: 'tuple' 和 'tuple'

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

猜我在元组/字符串格式上做错了什么。任何帮助表示赞赏!

【问题讨论】:

    标签: python mysql datetime


    【解决方案1】:

    看起来cursor.fetchone() 返回以字段元组形式呈现的记录。 在您的情况下,您只有一个字段(Timewhen),因此您有一个包含一个元素的元组。

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

    【讨论】:

      【解决方案2】:

      resultresult2 是表示从查询返回的整行的元组。在这种情况下,它们包含一个元素,因为您的查询仅包含一列。您可以使用[] 运算符提取此值。例如:

      result=cursor.fetchone()[0]
      

      【讨论】:

        猜你喜欢
        • 2012-06-10
        • 1970-01-01
        • 1970-01-01
        • 2013-02-01
        • 1970-01-01
        • 2021-11-25
        • 2011-08-01
        相关资源
        最近更新 更多