time
The time module provides a variety of time-related functions in Python. It lets you get the current time, measure elapsed time, pause execution, and convert between different time representations. Most functions in this module wrap the corresponding C library functions, making them fast and system-dependent.
Key Functions
time.time()
Returns the current time as a floating‑point number of seconds since the epoch (January 1, 1970, 00:00:00 UTC). Use it for timestamping events and measuring durations.
Syntax
time.time() -> float
Example
import time
timestamp = time.time()
print(f"Seconds since epoch: {timestamp}")
# Seconds since epoch: 1741614859.123456
# Calculate elapsed time
start = time.time()
# ... some operation ...
end = time.time()
print(f"Operation took {end - start:.3f} seconds")
time.sleep()
Suspends execution of the current thread for the given number of seconds. The argument can be a float for sub‑second precision.
Syntax
time.sleep(seconds: float) -> None
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seconds | float | — | Number of seconds to sleep. Can be zero or fractional; the actual sleep duration depends on system scheduling. |
Example
import time
print("Starting...")
time.sleep(2.5) # Wait 2.5 seconds
print("Done.")
time.perf_counter()
Return a high‑resolution performance counter for benchmarking short‑lived operations. The reference point is undefined, so only differences between calls are meaningful.
Syntax
time.perf_counter() -> float
Example
import time
start = time.perf_counter()
# ... code to measure ...
end = time.perf_counter()
print(f"Elapsed: {end - start:.6f} seconds")
time.localtime()
Convert a timestamp (seconds since epoch) to a struct_time in the local time zone. If no argument is given, uses the current time.
Syntax
time.localtime([seconds: float]) -> struct_time
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
seconds | float | time.time() | Timestamp to convert. |
Example
import time
now = time.localtime()
print(f"Year: {now.tm_year}, Month: {now.tm_mon}, Day: {now.tm_mday}")
print(f"Hour: {now.tm_hour}, Minute: {now.tm_min}, Second: {now.tm_sec}")
# Convert a specific timestamp
timestamp = 1609459200 # 2021-01-01 00:00:00 UTC
local = time.localtime(timestamp)
print(f"That timestamp corresponds to {local.tm_year}-{local.tm_mon:02d}-{local.tm_mday:02d}")
time.gmtime()
Like localtime, but returns a struct_time in UTC.
Syntax
time.gmtime([seconds: float]) -> struct_time
Example
import time
utc = time.gmtime()
print(f"UTC time: {utc.tm_hour:02d}:{utc.tm_min:02d}:{utc.tm_sec:02d}")
time.strftime()
Format a struct_time (or the current local time) into a human‑readable string according to a format specification.
Syntax
time.strftime(format: str, t: struct_time = localtime()) -> str
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
format | str | — | Format string with directives like %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second). |
t | struct_time | localtime() | Time tuple to format. |
Example
import time
now = time.localtime()
formatted = time.strftime("%Y-%m-%d %H:%M:%S", now)
print(f"Current time: {formatted}")
# Using default (current local time)
default_fmt = time.strftime("%A, %d %B %Y")
print(f"Today is {default_fmt}")
time.strptime()
Parse a string representing a time according to a format specification, returning a struct_time.
Syntax
time.strptime(string: str, format: str) -> struct_time
Example
import time
parsed = time.strptime("2025-12-31 23:59:59", "%Y-%m-%d %H:%M:%S")
print(f"Year: {parsed.tm_year}, Month: {parsed.tm_mon}, Day: {parsed.tm_mday}")
Common Patterns
Measuring Code Execution Time
Use perf_counter() for reliable timing of short operations:
import time
def expensive_function():
time.sleep(0.1) # Simulate work
start = time.perf_counter()
expensive_function()
end = time.perf_counter()
print(f"Function took {end - start:.3f} seconds")
Creating a Simple Timer
Combine time.time() with a context manager or a class:
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self.end = time.perf_counter()
self.elapsed = self.end - self.start
print(f"Elapsed time: {self.elapsed:.3f} seconds")
with Timer():
time.sleep(1)
Converting Between Representations
Convert a timestamp to a readable string:
import time
timestamp = time.time()
local = time.localtime(timestamp)
readable = time.strftime("%Y-%m-%d %H:%M:%S %Z", local)
print(f"Local time: {readable}")
Scheduling Periodic Tasks
Use sleep() to run a loop at regular intervals:
import time
interval = 5 # seconds
for i in range(3):
print(f"Cycle {i+1} at {time.strftime('%H:%M:%S')}")
time.sleep(interval)
Errors
ValueError– raised bystrptime()if the input string does not match the format.OverflowError– if a timestamp is out of the range supported by the platform’s Ctime_ttype.OSError– rarely,sleep()may be interrupted by a signal.