How to use 'time' in Python

Learn how to use time in Python. This guide covers different methods, tips, real-world applications, and how to debug common errors.

How to use 'time' in Python
Published on: 
Tue
Mar 3, 2026
Updated on: 
Fri
Mar 6, 2026
The Replit Team Logo Image
The Replit Team

Python's time functions are essential for many applications. They let you schedule tasks, timestamp logs, and measure code performance. These tools provide the precision required for time-sensitive operations.

In this article, you'll explore key techniques and practical tips. You'll see real-world applications and get advice to debug common time-related issues, so you can handle temporal data with confidence.

Using time.time() to get the current timestamp

import time
current_time = time.time()
print(f"Current timestamp: {current_time}")--OUTPUT--Current timestamp: 1711026125.4657292

The time.time() function returns the current time as a floating-point number. This isn't a human-readable date. Instead, it's a Unix timestamp representing the seconds passed since the epoch—midnight on January 1, 1970, UTC. This standard is fundamental for tracking time across many systems.

The decimal portion gives you sub-second precision, which is critical for tasks like performance profiling. Because it's a simple number, this raw format is highly efficient for calculations and storage before you convert it to a different format.

Common time functions

While raw timestamps are efficient, you'll often need functions to format time for readability or pause your script's execution to manage program flow.

Getting readable time with time.ctime()

import time
timestamp = time.time()
readable_time = time.ctime(timestamp)
print(f"Unix timestamp: {timestamp}")
print(f"Readable time: {readable_time}")--OUTPUT--Unix timestamp: 1711026125.4657292
Readable time: Thu Mar 21 12:35:25 2024

The time.ctime() function converts a Unix timestamp into a human-readable string. It’s a straightforward way to translate the raw seconds from time.time() into a format that's easy to understand at a glance.

  • It takes the timestamp as an argument. If you don't pass one, it automatically uses the current time.
  • The output is always a 24-character string with a standard format, like "Thu Mar 21 12:35:25 2024".

Formatting time with time.strftime()

import time
current_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
formatted_date = time.strftime("%A, %B %d, %Y", current_time)
print(formatted_time)
print(formatted_date)--OUTPUT--2024-03-21 12:35:25
Thursday, March 21, 2024

When you need full control over time formatting, time.strftime() is the tool for the job. It lets you build a custom string representation from a time structure object, which you get using time.localtime(). You simply pass a format string and the time object to the function.

  • The format string uses directives—like %Y for the year and %m for the month—to specify the output.
  • This gives you the flexibility to create any date and time format you need.

Creating delays with time.sleep()

import time
print("Starting...")
time.sleep(2) # Pause execution for 2 seconds
print("Finished after 2 seconds")--OUTPUT--Starting...
Finished after 2 seconds

The time.sleep() function pauses your script's execution for a set duration. It's a straightforward way to introduce a delay, which is useful for tasks like rate-limiting API calls or waiting for a background process to complete. The function takes a single argument representing the number of seconds to wait.

  • You can pass an integer, like time.sleep(2), to pause for whole seconds.
  • It also accepts a floating-point number for sub-second precision.

Advanced time techniques

Now that you've handled the basics, you're ready to tackle advanced techniques like measuring performance, managing timezones, and creating specific timestamps.

Measuring execution time with time.perf_counter()

import time

start_time = time.perf_counter()
# Simulate some computation
for _ in range(1_000_000):
pass
end_time = time.perf_counter()
print(f"Operation took {end_time - start_time:.6f} seconds")--OUTPUT--Operation took 0.023156 seconds

When you need to measure how long a piece of code takes to run, time.perf_counter() is your best choice. Unlike time.time(), it’s designed specifically for performance measurement. It provides a high-precision, monotonic clock that isn't affected by system time updates, ensuring your measurements are accurate.

  • You capture the time before and after your code runs.
  • The difference between the end_time and start_time gives you the precise execution duration.

Working with UTC and timezone differences

import time

local_time = time.localtime()
utc_time = time.gmtime()
print(f"Local: {time.strftime('%H:%M:%S', local_time)}")
print(f"UTC: {time.strftime('%H:%M:%S', utc_time)}")
print(f"Timezone offset: {time.timezone / 3600} hours")--OUTPUT--Local: 12:35:25
UTC: 17:35:25
Timezone offset: -5.0 hours

Managing timezones is crucial for applications that operate globally. Python's time module helps you distinguish between your system's local time and the universal standard, UTC. This ensures your timestamps are consistent and accurate, no matter where your code runs.

  • Use time.localtime() to get a time structure based on your local timezone.
  • Use time.gmtime() to get the equivalent time structure in UTC.
  • The time.timezone attribute provides the offset in seconds between your local timezone and UTC.

Creating specific time points with time.mktime()

import time

# Create timestamp for December 31, 2024 at 23:59:59
time_tuple = (2024, 12, 31, 23, 59, 59, 0, 0, 0)
timestamp = time.mktime(time_tuple)
future_time = time.ctime(timestamp)
seconds_until = timestamp - time.time()
print(f"Future time: {future_time}")
print(f"Seconds until then: {seconds_until:.0f}")--OUTPUT--Future time: Tue Dec 31 23:59:59 2024
Seconds until then: 24462514

The time.mktime() function lets you convert a structured time tuple into a Unix timestamp. This is perfect for creating a timestamp for a specific date, whether it's in the past or future. You can then use this timestamp for calculations, like finding the duration between now and a future event.

  • You start by defining a time_tuple with nine elements, from the year down to whether daylight saving is in effect.
  • The function takes this tuple and returns a floating point number representing the seconds since the epoch.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

Replit Agent can take the time functions covered in this article and build them into complete applications. For example, you could have it create:

  • A performance benchmarking utility that uses time.perf_counter() to measure and compare the execution speed of different Python functions.
  • A countdown calculator that takes a future date and uses time.mktime() to display the remaining time.
  • A world clock dashboard that leverages time.gmtime() and time.strftime() to show the current time across multiple timezones.

Simply describe your application idea, and Replit Agent will write the code, handle testing, and deploy it for you, all from your browser.

Common errors and challenges

Working with time can introduce subtle bugs, but you can avoid them by understanding a few common pitfalls.

Handling milliseconds with time.time()

While time.time() returns a float, the decimal part isn't a direct representation of milliseconds; it’s the fraction of a second. To reliably get milliseconds for more precise timing, you need to perform a simple calculation.

  • Multiply the full timestamp from time.time() by 1000.
  • Convert the result to an integer to get the total number of milliseconds since the epoch.

Timezone confusion when comparing timestamps

A frequent error is comparing timestamps from different timezones without a common reference, which can make events appear out of order. Although time.time() is based on UTC, functions like time.localtime() are timezone-aware, and mixing them carelessly can cause confusion.

Your best bet is to convert all timestamps to UTC before you store or compare them. This creates a consistent standard across your application.

Choosing the right timing function for performance measurement

Using time.time() to measure code speed is a common mistake because system time can change unexpectedly, skewing your results. For benchmarking, you should always use time.perf_counter() instead.

It uses a monotonic clock—a high-resolution timer that only moves forward and isn't affected by system time updates. This ensures the duration you measure reflects only the time your code took to run.

Handling milliseconds with time.time()

It’s a common mistake to assume time.time() returns milliseconds. The function actually returns seconds as a floating-point number. This can cause issues when you use a function like time.sleep(), which also expects seconds. The following code demonstrates this pitfall.

import time

current_ms = time.time()
print(f"Current time in milliseconds: {current_ms}")

time.sleep(100) # Trying to wait for 100 milliseconds

This code creates an unexpectedly long pause. Because time.sleep() accepts seconds, the script waits for 100 seconds, not the intended 100 milliseconds. The following example shows how to correctly implement a sub-second delay.

import time

current_ms = time.time() * 1000
print(f"Current time in milliseconds: {current_ms}")

time.sleep(0.1) # Correctly wait for 100 milliseconds

The solution is to pass time.sleep() a fractional number for sub-second delays. For instance, time.sleep(0.1) correctly pauses the script for 100 milliseconds. To get the time in milliseconds for other purposes, you can multiply the result of time.time() by 1000. Just remember not to pass that large number back into time.sleep(). This is key for any task requiring precise, short pauses, like managing API request rates.

Timezone confusion when comparing timestamps

Comparing timestamps seems simple, but it's easy to get wrong if you mix different time contexts. A common mistake involves using time.mktime() on a UTC time structure, which incorrectly applies a local timezone offset. The following code demonstrates this pitfall.

import time

utc_timestamp = time.mktime(time.gmtime())

now = time.time()
if now - utc_timestamp > 3600:
print("More than an hour has passed")

Here, time.mktime() incorrectly assumes the UTC time from time.gmtime() is local time, creating a skewed timestamp. The following example demonstrates the correct way to handle this conversion.

import time

utc_timestamp = time.mktime(time.gmtime())

now_utc = time.mktime(time.gmtime())
if now_utc - utc_timestamp > 3600:
print("More than an hour has passed")

The fix ensures you’re comparing apples to apples. By generating both timestamps with time.mktime(time.gmtime()), you keep them in the same frame of reference. Although each timestamp is individually skewed by the local timezone offset, they are skewed identically, which makes the comparison between them accurate. It’s a crucial reminder to maintain consistency when creating timestamps you intend to compare, especially when dealing with different time representations across your application.

Choosing the right timing function for performance measurement

It’s tempting to use time.time() for quick performance checks, but its reliance on system time makes it unreliable for benchmarking. System time can be adjusted forwards or backwards, which can corrupt your measurements. The following code illustrates this common mistake.

import time

start = time.time()
result = sum(range(10000))
end = time.time()
print(f"Operation took {end - start} seconds")

Because time.time() relies on the system clock, any adjustments made while your code runs can distort the measured duration between start and end. The following example shows a more reliable way to benchmark performance.

import time

start = time.perf_counter()
result = sum(range(10000))
end = time.perf_counter()
print(f"Operation took {end - start} seconds")

The fix is to use time.perf_counter() instead. It relies on a monotonic clock that’s not affected by system time changes, so the duration between your start and end markers is always accurate. This gives you a precise measurement reflecting only your code's execution time. You should always use this function for benchmarking to ensure your results are consistent and reliable, regardless of any system clock adjustments.

Real-world applications

Applying these concepts correctly allows you to build practical tools, such as a simple countdown timer or a utility for measuring download speeds.

Creating a simple countdown timer with time.sleep()

You can easily create a countdown timer by using time.sleep() inside a loop to pause the execution between each second.

import time

def countdown(seconds):
for remaining in range(seconds, 0, -1):
print(f"Time remaining: {remaining}s", end="\r")
time.sleep(1)
print("Time's up! ")

countdown(3)

This function builds a terminal-based countdown. It uses a for loop to count down from the specified number of seconds, pausing for one second with time.sleep(1) on each iteration.

  • The print function’s end="\r" argument is the key to the dynamic display. It moves the cursor to the start of the line without advancing.
  • This allows each new update to overwrite the previous one, creating a clean, single-line timer that updates in place.

Once the loop completes, a final message appears to signal that time is up.

Measuring download speed with time.time()

You can measure the speed of a file download by capturing the start and end times of the transfer with time.time().

import time

def simulate_download(size_mb):
start = time.time()
time.sleep(2) # Simulate network delay
end = time.time()
speed = size_mb / (end - start)
print(f"Downloaded {size_mb}MB in {end-start:.2f}s ({speed:.2f}MB/s)")

simulate_download(10)

This function puts the timing functions to practical use for calculating a rate. By subtracting the start timestamp from the end timestamp, you get the total duration of the simulated download.

  • The time.sleep(2) call is a stand-in for the actual download process, pausing the script for two seconds.
  • The download speed is then determined by dividing the file size (size_mb) by this duration.

Get started with Replit

Put these time functions to work by building a real tool. Just tell Replit Agent what you want, like “build a world clock dashboard” or “create a utility to benchmark function performance.”

The agent writes the code, tests for errors, and deploys your app directly from your browser. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.