find time difference in seconds as an integer with python

find time difference in seconds as an integer with python

import time
now = time.time()
...
later = time.time()
difference = int(later - now)

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

find time difference in seconds as an integer with python

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.

Leave a Reply

Your email address will not be published. Required fields are marked *