Python 3 How to Subtract Time

If you need to do simple time measurement - the start and the end of a given code and then to find the time difference between them - you can use standard python modules like time, datetime, date. In this article you can find 3 examples:

Subtract time in Python 3 by:

For more complex benchmarks you can check this articles:

Python 3 time subtract datetime

In this article we are going to measure the time of a given method by roughly getting the start and the end of the method. The example below shows the first way to achieve this:

from datetime import datetime
import time
start = datetime.now()
time.sleep(15)
end = datetime.now()

print(start)
print(end)
print(end - start)

result:

2018-10-15 12:26:28.159103
2018-10-15 12:26:43.159961
0:00:15.000858

as you can see the result is shown in full time and as a final difference in format: h:mm:ss.mmmmmmm. This is by using datetime and subtract of the two times.

Python 3 time subtract datetime combine

Another way to subtract dates in python is by using datetime method combine. The example below show the usage:

from datetime import datetime, date

start = datetime.now().time()
time.sleep(3)
end = datetime.now().time()

print(start)
print(end)
print(datetime.combine(date.min, end) - datetime.combine(date.min, start))

result:

12:41:38.755186
12:41:41.755358
0:00:03.000172

The difference is the here we measure the time only. You need to be careful if the start and the end are in different days or in another words - midnight is not passed.
If you give date instead of time you will get an error:

TypeError: combine() argument 2 must be datetime.time, not datetime.datetime

Python 3 time subtract timedelta

There is one more example which can be used. This example use time delta and you can see the code below:

from datetime import timedelta

start = datetime.now().time()
time.sleep(3)
end = datetime.now().time()

t1 = timedelta(hours=start.hour, minutes=start.minute, seconds=start.second)
t2 = timedelta(hours=end.hour, minutes=end.minute, seconds=end.second)

duration = t2 - t1

print(t1)
print(t2)
print(duration)

the result of this example is:

12:50:35
12:50:38
0:00:03

With this last example you can face two errors like:

t2 = timedelta(hours=end.hour, minutes=end.minute, seconds=end.sec)

AttributeError: 'datetime.time' object has no attribute 'sec'

t2 = timedelta(hours=end.hour, minutes=end.min, seconds=end.second)

TypeError: unsupported type for timedelta minutes component: datetime.time