0
0
PythonHow-ToBeginner · 3 min read

How to Use Time Module in Python: Syntax and Examples

Use the time module in Python by importing it with import time. It provides functions like time.sleep(seconds) to pause execution and time.time() to get the current time in seconds since the epoch.
📐

Syntax

The time module is imported using import time. Key functions include:

  • time.sleep(seconds): Pauses the program for the given number of seconds.
  • time.time(): Returns the current time in seconds since January 1, 1970 (epoch).
  • time.localtime(): Converts the current time to a readable struct_time object.
python
import time

# Pause for 2 seconds
time.sleep(2)

# Get current time in seconds since epoch
current_time = time.time()

# Convert to readable time
readable_time = time.localtime(current_time)

print(current_time)
print(readable_time)
💻

Example

This example shows how to pause a program for 3 seconds and then print the current time in a readable format.

python
import time

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

current_time = time.time()
print(f"Current time in seconds since epoch: {current_time}")

local_time = time.localtime(current_time)
print(f"Readable local time: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)}")
Output
Start End after 3 seconds Current time in seconds since epoch: 1700869274.123456 Readable local time: 2024-11-24 12:21:14
⚠️

Common Pitfalls

Common mistakes when using the time module include:

  • Using time.sleep() with a negative number, which causes an error.
  • Expecting time.time() to return a formatted date instead of a float timestamp.
  • Not converting timestamps to readable formats before printing.
python
import time

# Wrong: negative sleep time causes error
# time.sleep(-1)  # This will raise ValueError

# Right: positive sleep time
time.sleep(1)

# Wrong: printing raw timestamp without formatting
print(time.time())  # Outputs a float like 1700869274.123456

# Right: convert to readable string
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
📊

Quick Reference

FunctionDescription
time.sleep(seconds)Pause execution for given seconds
time.time()Get current time in seconds since epoch
time.localtime([secs])Convert seconds to struct_time (local time)
time.gmtime([secs])Convert seconds to struct_time (UTC)
time.strftime(format, t)Format struct_time to string
time.strptime(string, format)Parse string to struct_time

Key Takeaways

Import the time module with import time to access its functions.
Use time.sleep(seconds) to pause your program safely.
time.time() returns the current timestamp as a float number.
Convert timestamps to readable formats using time.localtime() and time.strftime().
Avoid negative values in time.sleep() to prevent errors.