import time
51 Time Module
51.1 Basic
51.1.1 What is the time
module?
The time
module gives you ways to work with time in your Python programs. This includes: - Getting the current time - Measuring elapsed time - Pausing your program’s execution - Converting between different time formats
time.time()
gives you the current time as seconds since the epochtime.sleep(seconds)
pauses your program for the specified durationlocaltime()
andgmtime()
convert epoch time to structured time objectsstrftime()
formats time objects into human-readable stringsperf_counter()
is best for precise performance measurementsprocess_time()
measures only CPU time used by your program
Let’s explore each of these functions with examples.
51.1.2 Getting the current time
The most basic function is time()
, which returns the current time as a floating-point number representing seconds since the “epoch” (January 1, 1970, 00:00:00 UTC):
= time.time()
current_time print(current_time) # Example output: 1712020642.7743263
1746977445.338582
This number by itself isn’t very readable, but it’s useful for calculations and can be converted to more human-readable formats.
51.1.3 Measuring elapsed time
A common use of the time
module is measuring how long something takes:
= time.time()
start_time
# Code you want to measure
for i in range(1_000_000):
pass
= time.time()
end_time = end_time - start_time
elapsed_time print(f"Operation took {elapsed_time:.6f} seconds")
Operation took 0.015958 seconds
51.2 Pausing execution with sleep()
To pause your program for a specified number of seconds:
print("Starting...")
2) # Pause for 2 seconds
time.sleep(print("Continuing after 2 seconds")
Starting...
Continuing after 2 seconds
This is useful for creating delays, implementing simple animations, or rate-limiting API calls.
51.3 Time conversions
51.3.1 Converting epoch time to a structured time
The localtime()
and gmtime()
functions convert a time expressed in seconds since the epoch to a structured time:
= time.time()
current_time = time.localtime(current_time) # Local time
local_time = time.gmtime(current_time) # UTC time
utc_time
print(local_time)
print(utc_time)
time.struct_time(tm_year=2025, tm_mon=5, tm_mday=11, tm_hour=22, tm_min=30, tm_sec=47, tm_wday=6, tm_yday=131, tm_isdst=0)
time.struct_time(tm_year=2025, tm_mon=5, tm_mday=11, tm_hour=15, tm_min=30, tm_sec=47, tm_wday=6, tm_yday=131, tm_isdst=0)
These functions return a struct_time
object, which has named attributes like tm_year
, tm_mon
, etc.
51.3.2 Converting to human-readable format
The strftime()
function formats time according to specified format codes:
= time.localtime()
local_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
formatted_time print(formatted_time) # Example output: 2025-04-02 10:30:42
2025-05-11 22:30:47
Common format codes:
%Y
: 4-digit year (e.g., 2025)%m
: Month (01-12)%d
: Day (01-31)%H
: Hour in 24-hour format (00-23)%M
: Minute (00-59)%S
: Second (00-59)%A
: Weekday name (e.g., Wednesday)%B
: Month name (e.g., April)
51.3.3 Converting string to time
The strptime()
function parses a string representation of time:
= "2025-04-02 10:30:42"
time_string = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
parsed_time print(parsed_time) # Returns a struct_time object
51.3.4 Performance measurement with perf_counter()
For more precise timing, especially for benchmarking code, use perf_counter()
:
= time.perf_counter()
start # Code to measure
0.1) # Just as an example
time.sleep(= time.perf_counter()
end print(f"Operation took {end - start:.6f} seconds")
Operation took 0.105405 seconds
perf_counter()
is more accurate than time()
for measuring short durations and isn’t affected by system clock changes.
51.3.5 Processor time with process_time()
To measure only CPU time used by your program (excluding sleep time):
= time.process_time()
start # Code to measure
1) # This won't be counted in process_time
time.sleep(= time.process_time()
end print(f"CPU time used: {end - start:.6f} seconds")
CPU time used: 0.001698 seconds
51.4 Example
51.4.1 Countdown
def countdown(seconds):
"""
Count down from the specified number of seconds.
Parameters
----------
seconds : int
Number of seconds to count down from
"""
print(f"Countdown starting from {seconds} seconds...")
for remaining in range(seconds, 0, -1):
print(f"{remaining} seconds remaining")
1)
time.sleep(
print("Time's up!")
# Usage
5) countdown(
Countdown starting from 5 seconds...
5 seconds remaining
4 seconds remaining
3 seconds remaining
2 seconds remaining
1 seconds remaining
Time's up!