What is the Time Library in Python? A Helpful Guide

Navigate to:

As a developer, you’ll often be tasked with dealing with time-related operations, be it displaying the current time, manipulating local time, calculating the time difference between two dates, etc. Python provides a time library out of the box that developers can use to handle time-related operations such as working timestamps, measuring time intervals, and manipulating time in various ways. In this guide, we’ll explore the basics of the time library, its key functions, and practical use cases.

What Is the Time Library in Python?

The time library in Python is a module that provides various functions to work with time-related operations. It’s part of the Python Standard Library. This means that you can simply import this module and start using it without having to install any additional modules. You can use the time library for any tasks that involve calculations with date and time, scheduling operations, measuring the execution of your code, etc.

Exploring Time Library: Common Functions

Let’s take a look at some of the most commonly used functions of the time library with some examples.

1. time()

You can use the time() function to return the current time in seconds. It measures the current time since the beginning of the epoch, a predefined point in time that often dates back to January 1, 1970, at 00:00:00 (UTC). To return the current time, simply call the function time() in the time module. You can use the following to output the current time:

import time
current_time = time.time()
print("Current time in seconds since the epoch:", current_time)

The above code should output the current time in seconds as shown below:

Current time in seconds since the epoch: 1694622847.212096

2. ctime()

A lot of times you need to display time in a more human-readable format. You can use the ctime() function to return a string that represents the current local time in a human-readable format. It tells you the day of the week followed by the date, the time, and the year. You can use the following to output the current time:

import time
current_local_time = time.ctime()
print("Current local time:", current_local_time)

The above code should output the current time in a readable format as shown below:

Current local time: Wed Sep 13 22:05:11 2023

3. gmtime()

When you’re writing code that will run in different parts of the world, you need to represent time in a consistent format. In order to maintain a consistent and accurate time reference that’s followed through different regions and time zones, developers often represent time in a format known as UTC, short for Coordinated Universal Time. It’s a time standard that serves as a basis for timekeeping worldwide.

You can use the gmtime() function to return a time tuple representing the current UTC time. The time tuple contains the following attributes:

  • tm_year
  • tm_mon
  • tm_mday
  • tm_hour
  • tm_min
  • tm_sec
  • tm_wday
  • tm_yda
  • tm_isdt
  • tm_zone
  • tm_gmtoff

Consider the example below:

import time
current_utc_time = time.gmtime()
print("Current UTC time:", current_utc_time)

It generates the following output:

Current UTC time: time.struct_time(tm_year=2023, tm_mon=9, tm_mday=13, tm_hour=16, tm_min=45, tm_sec=5, tm_wday=2, tm_yday=256, tm_isdst=0)

As you can see, tm_mon represents the month of the year, tm_mday represents the date, tm_hour represents the hour, etc., all in UTC format.

4. asctime()

Earlier you saw that the gmtime function provides the time in UTC, but it returns only a time tuple. For the end user, a tuple or struct_time is of no use. You can use the asctime() function to convert a time tuple or struct_time to a string in a human-readable format. Let’s use the previous example to display UTC time in a human-readable format:

import time
current_time_tuple = time.gmtime()
current_time_string = time.asctime(current_time_tuple)
print("Current UTC time as a string:", current_time_string)

If you run the code above, you should get the same UTC time in a human-readable format:

Current UTC time as a string: Wed Sep 13 17:27:31 2023

5. mktime()

You can use the mktime() function to convert a time tuple into seconds since the beginning of the epoch. If, for example, you have the time_tumple shown below, you can convert it to seconds using the following code:

import time
time_tuple = (2023, 9, 9, 12, 0, 0, 0, 0, 0)
epoch_time = time.mktime(time_tuple)
print("Epoch time:", epoch_time)

That should give you the epoch time in seconds from the converted tuple:

Epoch time: 1694241000.0

6. sleep()

Sometimes you need to delay the execution of some code for a specified amount of time. Adding delays is a common use case for adding rate limits to your APIs to ensure that they don’t exceed the allowed request rate. For example, if an API allows one hundred requests per minute, you can add a delay between each request to stay within the limit. You can also use delays in multi-threaded or multi-process applications to introduce delays between concurrent tasks. This can help prevent the overloading of resources or contention issues.

For such scenarios, you can use the sleep() function to delay the execution of some code for a specific number of seconds. Below is a simple example that prints “Start” at the time of execution of the code and “End” after two seconds:

import time
print("Start")
time.sleep(2)  # Sleep for 2 seconds
print("End")

(image)

7. strftime()

You can also convert a time tuple or struct_time to a specific format-based string using the strftime function. Consider the example below. Here we will display the current UTC time in a format where the time is displayed by year, month, day and time using the strftime function:

import time
current_time_tuple = time.gmtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time_tuple)
print("Formatted UTC time:", formatted_time)

The code above should display the time tuple in the specified format shown below:

Formatted UTC time: 2023-09-14 05:08:48

8. strptime()

You can even do the reverse of the previous operation. If you have a time string that you want to convert to a time tuple, you can use the strptime() function, which parses a string representing a date and time and returns a time tuple. You can then use the time tuple to extract the specific day, year, month, etc. from the time or do any other manipulation.

import time
time_string = "2023-09-09 12:00:00"
time_tuple = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print("Parsed time tuple:", time_tuple)

General Use Cases for the Python Time Library

Now that you have a basic understanding of some of the common time functions, let’s look at some popular use cases.

Date and Time Calculations

You can use the mktime function to calculate the time difference in seconds between two time tuples as shown below:

import time
start_time = time.mktime((2023, 9, 1, 0, 0, 0, 0, 0, 0))
end_time = time.mktime((2023, 9, 9, 0, 0, 0, 0, 0, 0))
time_difference = end_time - start_time
print("Time difference in seconds:", time_difference)

When you run the code above, you’ll see the time difference outputted to the console that represents the difference in seconds between the two time tuples:

Time difference in seconds: 691200.0

Calculating the time difference can be used in a number of places, especially when displaying information about when an action was completed. For example, you can calculate the time difference between the current time and the time a user updated their information and use that difference to convey when the information was updated last.

Data Logging with Timestamps

In IoT and other electronic applications, you might need to log a timestamp with data such as information from a sensor or other hardware like temperature, humidity, etc. You can use the strftime1 function to output the local time in a human-readable format and log it alongside the sensor data.

Here’s an example:

import time

def log_sensor_data(sensor_value):
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(f"{current_time}: Sensor value: {sensor_value}")

# Simulate sensor data
for i in range(1, 6):
    sensor_data = i * 10
    log_sensor_data(sensor_data)

And here’s how the above code would run and display the logged sensor data along with the timestamps:

2023-09-14 10:51:53: Sensor value: 10
2023-09-14 10:51:53: Sensor value: 20
2023-09-14 10:51:53: Sensor value: 30
2023-09-14 10:51:53: Sensor value: 40
2023-09-14 10:51:53: Sensor value: 50

Profiling and Benchmarking Code

You can use the timefunction to generate two times, one that marks the beginning of the execution of some code and another that marks the end. You can then calculate the difference between the two times to determine the time it took the codeblock to execute.

import time

def expensive_function():
    time.sleep(2)

start_time = time.time()
expensive_function()
end_time = time.time()
execution_time = end_time - start_time
print("Execution time:", execution_time, "seconds")

Note how we’re also using the sleep function to induce an explicit delay to mimic an expensive function execution. The above code should give you an execution time of two seconds:

Execution time: 2.0070152282714844 seconds

FAQ

How do I get the time library in Python?

The time library is part of the Python Standard Library, so you don’t need to install it separately. You can simply import it using import time.

What is the import time library in Python?

import time is the Python statement used to import the time library, making its functions and classes available for use in your code.

How does time() work in Python?

The time() function in Python returns the current time in seconds since the beginning of the epoch. It allows you to measure time intervals, benchmark code, and track time-related data within your programs.

This post was written by Siddhant Varma. Siddhant is a full stack JavaScript developer with expertise in frontend engineering. He’s worked with scaling multiple startups in India and has experience building products in the Ed-Tech and healthcare industries. Siddhant has a passion for teaching and a knack for writing. He’s also taught programming to many graduates, helping them become better future developers.