Python Time


Python provides a built-in module called time to work with time-related tasks like delays, timestamps, and performance measurement.

You need to import it before use:

import time

🔹 Get Current Time (Epoch)

print(time.time())

⏱️ Returns number of seconds since January 1, 1970 (Unix Epoch).


🔹 Sleep / Delay Execution

print("Start")
time.sleep(2)
print("End after 2 seconds")

🔹 Get Local Time

local = time.localtime()
print(local)

🔹 Format Time Readably

print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
Code Meaning
%Y Year (2025)
%m Month (06)
%d Day (21)
%H Hour (24-hour)
%I Hour (12-hour)
%M Minutes
%S Seconds
%p AM/PM

🔹 Convert to Timestamp

t = time.strptime("21 Jun 25", "%d %b %y")
print(t)

🔹 Performance Timer

start = time.perf_counter()
# your code here
end = time.perf_counter()
print("Execution time:", end - start)

🔹 CPU Sleep in Loop

for i in range(5):
    print(i)
    time.sleep(1)  # wait 1 second

🧪 Try It Yourself

Use sleep() to delay output, format current time, and calculate code execution time.


Practice Questions

Q1. Write a Python program to import the time module.

Q2. Write a Python program to print the current Unix timestamp using time.time().

Q3. Write a Python program to pause the execution for 3 seconds using time.sleep(3).

Q4. Write a Python program to format and print the local time as HH:MM:SS using time.strftime().

Q5. Write a Python program to show the full current date and time using strftime().

Q6. Write a Python program to use sleep() inside a loop of 5 iterations, printing the count each second.

Q7. Write a Python program to convert the string "15 Aug 25" to a time struct using time.strptime().

Q8. Write a Python program to use perf_counter() to measure execution time of a code block.

Q9. Write a Python program to get local time using time.localtime() and print it.

Q10. Write a Python program to print only the current minute and second from the current time.


Go Back Top