Python .time()

Anonymous contributor's avatar
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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

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 datetime
import time
# Create a simple timer for brewing tea
def brew_tea():
# Get start time
start_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 seconds
end_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:54
Brewing...
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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours