Measure Elapsed Time and Time Differences in Python
In Python, to measure elapsed time or to calculate the time difference between two date-times, use the standard library's time module and datetime module. Elapsed time and time differences can be represented in seconds or days.
Measure elapsed time
To obtain UNIX time (epoch seconds) as a floating-point number (float
), use the time()
function from the time
module.
import time
ut = time.time()
print(ut)
# 1549281692.9876952
print(type(ut))
# <class 'float'>
UNIX time refers to the number of seconds elapsed since 00:00:00 on January 1, 1970, in Coordinated Universal Time (UTC). It can be converted to and from datetime
objects.
The return value of time.time()
is a floating-point number with millisecond and microsecond information in the decimal part. However, be aware that the accuracy depends on the system as stated in the official documentation.
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.
time.time() — Time access and conversions — Python 3.11.3 documentation
Using time.time()
, you can measure elapsed time within a Python program.
Store the starting UNIX time in a variable using time.time()
, and calculate the difference by measuring the UNIX time again at the desired moment to obtain the elapsed time.
start = time.time()
time.sleep(3)
t = time.time() - start
print(t)
# 3.001929998397827
In this example, the process is paused using time.sleep()
.
Note that there is also a timeit module for measuring code execution time. It automatically measures repeatedly and outputs averages, making it more suitable for evaluating processing speed.
If you only need to log the time taken for a process, using time.time()
is appropriate.
Calculate the time difference between date-times
To calculate the time difference between two date-times rather than specifying the start and end timings in the program, use the datetime
module.
The datetime
module provides a datetime
type for representing dates and times, as well as a date
type for representing dates. Subtracting these objects from each other creates a timedelta
object representing the time difference.
Subtract datetime
objects
For datetime
objects:
import datetime
dt1 = datetime.datetime(year=2017, month=10, day=10, hour=15)
print(dt1)
# 2017-10-10 15:00:00
print(type(dt1))
# <class 'datetime.datetime'>
dt2 = datetime.datetime(year=2019, month=1, day=1, hour=12)
print(dt2)
# 2019-01-01 12:00:00
td = dt2 - dt1
print(td)
# 447 days, 21:00:00
print(type(td))
# <class 'datetime.timedelta'>
timedelta
objects have days
, seconds
, and microseconds
attributes. You can also obtain the total number of seconds using the total_seconds()
method.
print(td.days)
# 447
print(td.seconds)
# 75600
print(td.microseconds)
# 0
print(td.total_seconds())
# 38696400.0
The timedelta
object can have negative values depending on the order of subtraction. A negative timedelta
object has a negative days
value and positive seconds
and microseconds
values.
td_m = dt1 - dt2
print(td_m)
# -448 days, 3:00:00
print(td_m.days)
# -448
print(td_m.seconds)
# 10800
print(td_m.total_seconds())
# -38696400.0
The built-in function abs()
can be applied to timedelta
objects. To easily obtain the time difference in days or seconds without considering the order of subtraction, use abs()
.
td_abs = abs(dt1 - dt2)
print(td_abs)
# 447 days, 21:00:00
print(td_abs.days)
# 447
print(td_abs.seconds)
# 75600
print(td_abs.total_seconds())
# 38696400.0
Subtract date
objects
The same applies to date
objects.
d1 = datetime.date(year=2017, month=10, day=10)
print(d1)
# 2017-10-10
print(type(d1))
# <class 'datetime.date'>
d2 = datetime.date(year=2019, month=1, day=1)
print(d2)
# 2019-01-01
td = abs(d1 - d2)
print(td)
# 448 days, 0:00:00
print(type(td))
# <class 'datetime.timedelta'>
Subtract datetime
objects and date
objects
Subtracting a datetime
object from a date
object results in an error.
# print(dt2 - d1)
# TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
You need to match the types of the objects.
A datetime
object can be converted to a date
object using the date()
method, but the time information is lost.
print(dt2.date())
# 2019-01-01
print(type(dt2.date()))
# <class 'datetime.date'>
print(dt2.date() - d1)
# 448 days, 0:00:00
A datetime
object can be created from a date
object and a time
object using datetime.combine()
.
A time
object can be created using a constructor time()
. If you omit the constructor arguments, it becomes 00:00:00
. If you want to specify a different time, provide the hour
, minute
, second
, and microsecond
arguments.
print(datetime.datetime.combine(d1, datetime.time()))
# 2017-10-10 00:00:00
print(type(datetime.datetime.combine(d1, datetime.time())))
# <class 'datetime.datetime'>
print(dt2 - datetime.datetime.combine(d1, datetime.time()))
# 448 days, 12:00:00
Time difference between the current time and a specific date-time
You can obtain the current datetime
object or date
object with datetime.now()
or date.today()
.
Using these, you can calculate the time difference between the current time and a specific date-time.
print(datetime.datetime.now() - dt2)
# 34 days, 9:30:07.362784
print(datetime.date.today() - d2)
# 34 days, 0:00:00
You can compare the current time with a past or future date-time. As mentioned above, if you want to obtain the time difference as an absolute value, use abs()
.
Calculate date-times with added or subtracted time differences
timedelta
objects can be used for arithmetic operations such as addition and subtraction with datetime
objects or date
objects. For example, you can easily calculate and obtain the date one week ago, the date 10 days later, or the time 50 minutes later.
You can create a timedelta
object with a specified time difference by providing days, hours, seconds, etc., to the constructor.
The arguments you can specify are weeks
, days
, hours
, minutes
, seconds
, milliseconds
, and microseconds
. If you omit them, they are considered 0
.
td = datetime.timedelta(weeks=1, hours=20)
print(td)
# 7 days, 20:00:00
print(type(td))
# <class 'datetime.timedelta'>
You can use this for arithmetic operations with datetime
objects or date
objects.
print(dt1)
# 2017-10-10 15:00:00
print(dt1 + td)
# 2017-10-18 11:00:00
print(dt1 - td)
# 2017-10-02 19:00:00
When performing arithmetic operations with date
objects, be aware that the time information of the timedelta
object is ignored.
print(d1)
# 2017-10-10
print(d1 + td)
# 2017-10-17
print(d1 - td)
# 2017-10-03