The time
module in Python provides various time-related functions. It allows you to work with time-related tasks like getting the current time, measuring the execution time of a code block, and suspending the execution of a program.
Table of Contents
- Introduction
- Key Functions
time()
ctime()
gmtime()
localtime()
mktime()
strftime()
strptime()
sleep()
perf_counter()
process_time()
time_ns()
- Examples
- Getting the Current Time
- Converting Between Time Representations
- Formatting Time
- Measuring Execution Time
- Suspending Execution
- Real-World Use Case
- Conclusion
- References
Introduction
The time
module provides various functions to work with time-related tasks. It includes functions to get the current time, format time, parse time strings, and measure execution time. This module is essential for applications that require precise time management or time-based operations.
Key Functions
time()
Returns the current time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC).
import time
current_time = time.time()
print(f'Current time in seconds since the Epoch: {current_time}')
Output:
Current time in seconds since the Epoch: 1722067106.002618
ctime()
Converts a time expressed in seconds since the Epoch to a string representing local time.
import time
time_str = time.ctime()
print(f'Current time: {time_str}')
Output:
Current time: Sat Jul 27 13:28:26 2024
gmtime()
Converts a time expressed in seconds since the Epoch to a struct_time
in UTC.
import time
gmtime_struct = time.gmtime()
print(f'UTC time: {gmtime_struct}')
Output:
UTC time: time.struct_time(tm_year=2024, tm_mon=7, tm_mday=27, tm_hour=7, tm_min=58, tm_sec=26, tm_wday=5, tm_yday=209, tm_isdst=0)
localtime()
Converts a time expressed in seconds since the Epoch to a struct_time
in local time.
import time
localtime_struct = time.localtime()
print(f'Local time: {localtime_struct}')
Output:
Local time: time.struct_time(tm_year=2024, tm_mon=7, tm_mday=27, tm_hour=13, tm_min=28, tm_sec=26, tm_wday=5, tm_yday=209, tm_isdst=0)
mktime()
Converts a struct_time
to seconds since the Epoch.
import time
time_struct = time.localtime()
epoch_seconds = time.mktime(time_struct)
print(f'Seconds since the Epoch: {epoch_seconds}')
Output:
Seconds since the Epoch: 1722067106.0
strftime()
Formats a struct_time
or tuple
representing a time to a string according to a format specification.
import time
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(f'Formatted time: {formatted_time}')
Output:
Formatted time: 2024-07-27 13:28:26
strptime()
Parses a string representing a time according to a format specification and returns a struct_time
.
import time
time_str = '2021-08-19 12:34:07'
time_struct = time.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print(f'Parsed time: {time_struct}')
Output:
Parsed time: time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=12, tm_min=34, tm_sec=7, tm_wday=3, tm_yday=231, tm_isdst=-1)
sleep()
Suspends execution for the given number of seconds.
import time
print('Sleeping for 2 seconds...')
time.sleep(2)
print('Awake now!')
Output:
Sleeping for 2 seconds...
Awake now!
perf_counter()
Returns the value (in fractional seconds) of a performance counter, which can be used to measure elapsed time with high resolution.
import time
start = time.perf_counter()
# Simulate a task
time.sleep(1)
end = time.perf_counter()
print(f'Task took {end - start:.4f} seconds')
Output:
Task took 1.0008 seconds
process_time()
Returns the sum of the system and user CPU time of the current process.
import time
start = time.process_time()
# Simulate a CPU-bound task
for _ in range(1000000):
pass
end = time.process_time()
print(f'CPU time used: {end - start:.4f} seconds')
Output:
CPU time used: 0.0000 seconds
time_ns()
Returns the current time in nanoseconds since the Epoch.
import time
current_time_ns = time.time_ns()
print(f'Current time in nanoseconds since the Epoch: {current_time_ns}')
Output:
Current time in nanoseconds since the Epoch: 1722067109474271900
Examples
Getting the Current Time
import time
current_time = time.time()
print(f'Current time in seconds since the Epoch: {current_time}')
Output:
Current time in seconds since the Epoch: 1722067109.5127213
Converting Between Time Representations
import time
# Get the current time as a struct_time in UTC
gmtime_struct = time.gmtime()
print(f'UTC time: {gmtime_struct}')
# Convert struct_time to seconds since the Epoch
epoch_seconds = time.mktime(gmtime_struct)
print(f'Seconds since the Epoch: {epoch_seconds}')
# Convert seconds since the Epoch to local time struct_time
localtime_struct = time.localtime(epoch_seconds)
print(f'Local time: {localtime_struct}')
Output:
UTC time: time.struct_time(tm_year=2024, tm_mon=7, tm_mday=27, tm_hour=7, tm_min=58, tm_sec=29, tm_wday=5, tm_yday=209, tm_isdst=0)
Seconds since the Epoch: 1722047309.0
Local time: time.struct_time(tm_year=2024, tm_mon=7, tm_mday=27, tm_hour=7, tm_min=58, tm_sec=29, tm_wday=5, tm_yday=209, tm_isdst=0)
Formatting Time
import time
# Format the current local time
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(f'Formatted time: {formatted_time}')
# Parse a time string to struct_time
time_str = '2021-08-19 12:34:07'
time_struct = time.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print(f'Parsed time: {time_struct}')
Output:
Formatted time: 2024-07-27 13:28:29
Parsed time: time.struct_time(tm_year=2021, tm_mon=8, tm_mday=19, tm_hour=12, tm_min=34, tm_sec=7, tm_wday=3, tm_yday=231, tm_isdst=-1)
Measuring Execution Time
import time
# Measure the time taken by a task
start = time.perf_counter()
# Simulate a task
time.sleep(1)
end = time.perf_counter()
print(f'Task took {end - start:.4f} seconds')
Output:
Task took 1.0004 seconds
Suspending Execution
import time
print('Sleeping for 2 seconds...')
time.sleep(2)
print('Awake now!')
Output:
Sleeping for 2 seconds...
Awake now!
Real-World Use Case
Logging with Timestamps
When logging events in an application, you might want to include timestamps to know when each event occurred.
import time
def log_event(event):
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(f'[{timestamp}] {event}')
# Example usage
log_event('Application started')
time.sleep(1)
log_event('Task completed')
Output:
[2024-07-27 13:28:32] Application started
[2024-07-27 13:28:33] Task completed
Measuring Function Execution Time
You can use perf_counter
to measure how long a function takes to execute.
import time
def example_function():
time.sleep(2)
start = time.perf_counter()
example_function()
end = time.perf_counter()
print(f'Function execution took {end - start:.4f} seconds')
Output:
Function execution took 2.0008 seconds
Conclusion
The time
module in Python provides a comprehensive set of tools for working with time-related tasks. It allows you to get the current time, convert between different time representations, format time, parse time strings, measure execution time, and suspend execution. This makes it a valuable module for any application that needs to work with time.