find time difference in seconds as an integer with python

Question:

I need to find the time difference in seconds with python. I know I can get the difference like this:

from datetime import datetime
now = datetime.now()
....
....
....
later = datetime.now()
difference = later-now

how do I get difference in total seconds?

Asked By: Richard

||

Answers:

import time
now = time.time()
...
later = time.time()
difference = int(later - now)
Answered By: Michael Mior

If all you need is to measure a time span, you may use time.time() function which returns seconds since Epoch as a floating point number.

Answered By: rkhayrov

The total_seconds method will return the difference, including any fractional part.

from datetime import datetime
now = datetime.now()
...
later = datetime.now()
difference = (later - now).total_seconds()

You can convert that to an integer via int() if you want

Answered By: Robert Longson

Adding up the terms of the timedelta tuple with adequate multipliers should give you your answer. diff.days*24*60*60 + difference.seconds

from datetime import datetime
now = datetime.now()
...
later = datetime.now()
diff = later-now
diff_in_seconds = diff.days*24*60*60 + diff.seconds

The variable ‘diff’ is a timedelta object that is a tuple of (days, seconds, microseconds) as explained in detail here https://docs.python.org/2.4/lib/datetime-timedelta.html. All other units (hours, minutes..) are converted into this format.

>> diff = later- now
>> diff
datetime.timedelta(0, 8526, 689000)
>> diff_in_seconds = diff.days*24*60*60 + diff.seconds
>> diff_in_seconds
>> 8527

Another way to look at it would be if instead of later-now (therefore a positive time difference), you instead have a negative time difference (earlier-now), where the time elapsed between the two is still the same as in the earlier example

>> diff = earlier-now
>> diff
datetime.timedelta(-1, 77873, 311000)
>> diff_in_seconds = diff.days*24*60*60 + diff.seconds
>> diff_in_seconds
>> -8527

Hence, even if we are sure the duration is less than 1 day, it is necessary to take the day term into account, since it is an important term in case of negative time difference.

Answered By: Jiaconda
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.