Python Time


In Python, the time module is used to work with time-related tasks, including measuring execution time, formatting timestamps, creating delays, and handling system time. While the datetime module focuses on dates and times, the time module provides low-level functionality for time-related operations and working with timestamps in seconds.

This tutorial will guide you through the core functions, methods, and practical applications of the Python time module.

Importing the time Module

The time module is built-in and does not require installation. To use it, simply import it:

import time

What is Timestamps

A timestamp is a float value representing the number of seconds since January 1, 1970, 00:00:00 UTC, also called the Unix epoch. Timestamps are useful for storing and comparing time data efficiently.

import time

current_timestamp = time.time()
print(current_timestamp)  # Example: 1760000000.123456

You can convert timestamps into readable formats using ctime() or localtime().

Getting Current Time

Using time.localtime()

localtime() returns a struct_time object containing components of local time:

local_time = time.localtime()
print(local_time)
print(local_time.tm_hour, local_time.tm_min, local_time.tm_sec)

struct_time has the following attributes:

Attribute Description
tm_year Year (e.g., 2025)
tm_mon Month (1–12)
tm_mday Day of the month (1–31)
tm_hour Hour (0–23)
tm_min Minute (0–59)
tm_sec Second (0–61)
tm_wday Weekday (0=Monday, 6=Sunday)
tm_yday Day of the year (1–366)
tm_isdst Daylight Saving Time flag

Using time.ctime()

ctime() converts a timestamp into a human-readable string:

print(time.ctime())  # Example: Thu Nov 20 14:30:15 2025

Pausing Execution with sleep()

The sleep() function delays program execution for a specified number of seconds:

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

This is useful for creating timers, animations, or waiting between network requests.

Measuring Execution Time

The time module allows you to measure how long a program or function takes to run:

start = time.time()

# Some code to measure
sum = 0
for i in range(1000000):
    sum += i

end = time.time()
print("Execution time:", end - start, "seconds")

For more precise measurements, you can use time.perf_counter().

Converting Between Time Formats

The time module provides several functions to convert between timestamps, struct_time, and string representations.

time.gmtime()

Converts a timestamp to UTC struct_time:

utc_time = time.gmtime()
print(utc_time)

time.mktime()

Converts a struct_time back into a timestamp:

import time

local_time = time.localtime()
timestamp = time.mktime(local_time)
print(timestamp)

time.strftime()

Formats struct_time or localtime into a readable string:

formatted = time.strftime("%d-%m-%Y %H:%M:%S", time.localtime())
print(formatted)  # Output: 20-11-2025 14:30:15

time.strptime()

Parses a string into a struct_time object:

time_str = "20-11-2025 14:30:15"
parsed_time = time.strptime(time_str, "%d-%m-%Y %H:%M:%S")
print(parsed_time)

Using perf_counter() and process_time()

  • perf_counter() – returns the most precise timer for measuring short durations:

start = time.perf_counter()
# Some code
end = time.perf_counter()
print("Elapsed time:", end - start)
  • process_time() – measures CPU time used by the program:

start = time.process_time()
# Some code
end = time.process_time()
print("CPU time:", end - start)

These functions are ideal for benchmarking and performance analysis.

Time Arithmetic

You can perform simple arithmetic using timestamps and timedelta equivalents:

import time

current_time = time.time()
future_time = current_time + 3600  # 1 hour later
print("Future timestamp:", future_time)

For working with human-readable time, convert timestamps using localtime() or gmtime() first.

Practical Examples

  1. Creating a Countdown Timer:

import time

for i in range(5, 0, -1):
    print(i)
    time.sleep(1)
print("Time's up!")
  1. Measuring Program Speed:

import time

start = time.perf_counter()
[sum(range(1000)) for _ in range(1000)]
end = time.perf_counter()
print("Execution time:", end - start)
  1. Formatting Current Time:

formatted_time = time.strftime("%H:%M:%S %p")
print("Current time:", formatted_time)
  1. Waiting for a Specific Event:

import time

print("Waiting for 5 seconds...")
time.sleep(5)
print("Done waiting!")
  1. Calculating Time Differences:

start = time.time()
time.sleep(3)
end = time.time()
print("Time difference:", end - start, "seconds")

Summary of the Tutorial

The Python time module is a versatile tool for working with timestamps, struct_time objects, and time delays. It allows you to:

  • Retrieve current time in various formats

  • Pause program execution using sleep()

  • Measure execution and CPU time

  • Convert between timestamps, strings, and struct_time

By mastering the time module, you can handle timing operations, performance measurements, and time-based scheduling effectively in Python. It is especially useful in automation scripts, performance benchmarking, and real-time applications.


Practice Questions

  1. Print the current timestamp using time.time().

  2. Convert the current timestamp to a readable local time using time.localtime().

  3. Format the current local time as "DD-MM-YYYY HH:MM:SS" using strftime().

  4. Pause the program for 5 seconds using time.sleep().

  5. Measure the execution time of a loop that sums numbers from 1 to 1,000,000 using time.time().

  6. Parse the string "20-11-2025 14:30:15" into a struct_time object using strptime().

  7. Convert a struct_time object back into a timestamp using time.mktime().

  8. Print the current UTC time using time.gmtime().

  9. Create a countdown timer that prints numbers from 10 to 1 with a 1-second delay.

  10. Measure the CPU processing time of a function using time.process_time().


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top