计算日期时间差python

时间:2016-06-20 17:52:31

标签: python date time difference

我正在编写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小时(约为65k秒)

>>> 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

1 个答案:

答案 0 :(得分: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