.time()
Anonymous contributor
Published Jun 7, 2022Updated Jan 29, 2025
Contribute to Docs
The datetime.time()
method returns a time in seconds that has passed since the epoch set on the computer. The .sleep()
function suspends execution of the current thread for the specified number of seconds.
Syntax
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
time.sleep(seconds)
The epoch is usually set as January 1, 1970, 00:00:00 (UTC)
on most operating systems, excluding any leap seconds.
Example
The following example demonstrates using datetime.time()
to track when tea brewing starts and ends, with .sleep()
creating a pause to simulate brewing time:
import datetimeimport time# Create a simple timer for brewing teadef brew_tea():# Get start timestart_time = datetime.datetime.now().time()print(f"Starting to brew tea at: {start_time.strftime('%H:%M:%S')}")print("Brewing...")time.sleep(3) # Wait for 3 secondsend_time = datetime.datetime.now().time()print(f"Tea is ready at: {end_time.strftime('%H:%M:%S')}")brew_tea()
The output of the above code will be:
Starting to brew tea at: 21:54:54Brewing...Tea is ready at: 21:54:57
Note: Times shown will reflect system’s current time.
Codebyte Example
Run the following code to get a better understanding of how .time()
and .sleep()
works:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours