Calculate date time difference python

2019-03-02 19:34发布

问题:

I am writing timediff function to calculate the time (seconds) difference between 2 giving date time

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)  

It seems to not take the "month, date, year" to the calculation. It gives the right calculation if it is in the same "month, date, year"

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

However with different "month, date, year", it gives the wrong answer. This only calculates time difference ~18hrs (which gives ~65k seconds)

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

Or 24hrs different it gives 0

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

The datetime takes the time format I gives

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

Am I missing anything?

I have another alternative which convert date time to seconds. But still want to know why this method doesnt work.

My alternative

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

Example:

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

回答1:

You need to use total_seconds() and not 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