2016-06-20 212 views
1

我寫timeDiff測量功能計算2捐贈日期時間計算日期時間差蟒蛇

def timediff(time1, time2): 
    timeformat = '%d%b%Y:%H:%M:%S' 
    #time1="01MAR2016:07:11:53" 
    #time2="01MAR2016:16:28:38" 

    try: 
     date_object1 = datetime.strptime(time1, timeformat) 
     date_object2 = datetime.strptime(time2, timeformat) 
    except ValueError: 
     print "time1 format: " + repr(time1) 
     print "time2 format: " + repr(time2) 
     raise      

    return abs((date_object2 - date_object1).seconds) 

之間的時間(秒)的區別似乎不採取「月,日,年」來計算。它提供了正確的計算,如果它是在相同的「月,日,年」

>>> t1="01MAR2016:07:11:53" 
>>> t2="01MAR2016:16:28:38" 
>>> timediff(t1, t2) 
33405 
不同

然而「月,日,年」,它給了錯誤的答案。這僅計算時間差〜18小時(可提供〜65000秒)

>>> t1="02APR2016:06:43:51" 
>>> t2="06APR2016:00:58:03" 
>>> timediff(t1, t2) 
65652 

或者24小時的不同它給0

>>> t1="01MAR2016:07:11:53" 
>>> t2="02MAR2016:07:11:53" 
>>> timediff(t1, t2) 
0 

日期時間花費的時間格式我給

>>> t1="01MAR2016:07:11:53" 
>>> t2="02MAR2016:07:11:53" 
>>> datetime.strptime(t1, timeformat) 
datetime.datetime(2016, 3, 1, 7, 11, 53) 
>>> datetime.strptime(t2, timeformat) 
datetime.datetime(2016, 3, 2, 7, 11, 53) 

上午我錯過了什麼?

我有另一種選擇將日期時間轉換爲秒。但仍然想知道爲什麼這種方法不起作用。

我的替代

def timediff(time1, time2): 
    timeformat = '%d%b%Y:%H:%M:%S' 
    t1 = datetime.strptime(time1, timeformat) 
    t2 = datetime.strptime(time2, timeformat) 

    return abs(time.mktime(t1.timetuple()) - time.mktime(t2.timetuple())) 

例子:

>>> t2 
'02MAR2016:07:11:53' 
>>> t1 
'01MAR2016:07:11:53' 
>>> timediff(t1,t2) 
86400.0 
+3

你正在使用'.seconds',而不是'.total_seconds( )' –

+0

你是對的!謝謝你的澄清。不知道有.total_seconds() – Nogcas

回答

5

您需要使用total_seconds()而不是seconds

>>> import datetime 
>>> f = '%d%b%Y:%H:%M:%S' 
>>> t1 = '01MAR2016:07:11:53' 
>>> t2 = '02MAR2016:07:11:53' 
>>> d1 = datetime.datetime.strptime(t1, f) 
>>> d2 = datetime.datetime.strptime(t2, f) 
>>> print(d2-d1) 
1 day, 0:00:00 
>>> print((d2-d1).total_seconds()) 
86400.0 
>>> print((d2-d1).seconds) 
0 
+0

打我寫一個答案,以及添加這裏是['timedelta.seconds']的文檔鏈接(https://docs.python.org/2/library/datetime.html# datetime.timedelta.resolution)「介於0和86399之間」和鏈接到['timedelta.total_seconds()'](https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds) –