ExampleEdit & Run

Use the time() function

#import the time module
import time

#print the number of seconds since the epoch
print(time.time())
copy
Output:
1739648939.6267583 [Finished in 0.010486533865332603s]

The time() function in the time module returns the number of seconds since the epoch (January 1st, 1970) as a floating point value. This can be useful in  measuring time for various purposes, such as benchmarking, timing algorithm execution, or simply to measure time elapsed since a certain point.

Syntax:
time()
copy

The function takes no argument.

Parameters:

The function returns a floating point value representing the number of seconds since the epoch up to the current moment.

ExampleEdit & Run

converting the returned seconds into a human-friendly date using the time.ctime() function

#import the module
import time

now = time.time()

#convert the seconds
current_date = time.ctime(now)

print(current_date)
copy
Output:
Sat Feb 15 22:48:59 2025 [Finished in 0.010168016888201237s]

Use the time() function to measure execution time

ExampleEdit & Run

Measuring execution time

import time

def delayed_add(a, b):
    start = time.time()
    result = a + b

    #delay the function using the sleep function
    time.sleep(1)
    end = time.time()
    print("Execution took %f seconds"%(end - start))
    return f"{a} + {b} = {result}"

print(delayed_add(10, 20))
copy
Output:
Execution took 1.000084 seconds 10 + 20 = 30 [Finished in 1.0106854513287544s]