Python

Python time module (Simple Examples)

Python’s time module plays a fundamental part in many applications of computer science. It allows you to perform some major functions efficiently and concisely.

You can calculate the performance of your code, suspend the execution of the thread in your program, or simply retrieve the current time when an event is triggered.

The time module also makes it easy to work with different time zones. You can switch between the Coordinated Universal Time (UTC) and the local time in your timezone using various functions.

This tutorial helps you understand the core concepts and functionalities offered by the Python time module.

To work with the time module, you need to import it into your program or working directory. To do this, run the following statement.

import time  

 

 

Get epoch time

Python’s time module has a time() function that returns the number of seconds that have passed since a certain epoch as a floating point number.

Before jumping into the example, you need to understand what an epoch is in the context of time functions.

The epoch represents the starting point against which you start to measure the time. This is platform dependent and varies for different operating systems.

For UNIX-based systems and most Windows systems, this is defined as January 1, 1970.

When you’re dealing with time functions, the epoch is considered a predefined datetime and is dependent upon the underlying platform or operating system.

We use the time() function that returns a floating point number. This value represents the number of seconds that have passed since the predefined epoch.

This number may vary depending on your OS. The returned value is not human-readable. It is useful in many situations such as when you want to measure the performance of your code.

You can calculate the difference between the values returned by the time function to measure the performance between two points in your code or to serialize the data for storage or transfer.

from time import time
time()

time function

 

Get current time

To convert the number returned by the time function into a readable form, you can use the ctime() function.

You pass the result of time() to this function and it returns a neat string with a set of values that represent the current local time, depending on your timezone and geographical location.

from time import time, ctime
epoch_time = time()
ctime(epoch_time)

ctime function

If you do not pass any value to ctime(), it uses as default, the value returned by time() function. The returned value is a string that represents a timestamp. It has a particular formatted structure which is described as follows:

[Day of the week, Month, Date of the Month, Hour, Minute, Second, Year]

 

Get UTC time

Coordinated Universal Time (UTC) is the time standard that is used as a reference to map time zones geographically.

Time zones make use of UTC and are calculated by adding or subtracting the offset from UTC. UTC was formerly known as Greenwich Mean Time (GMT).

It is easy and more intuitive to work with UTC since you do not need to worry about converting time in different time zones or geographical locations.

To get a UTC-based time in Python, you can use the gmtime() function. It takes as an argument the number of seconds and returns the UTC-based time representation of the argument.

When you pass 0 as the argument, it returns the epoch itself.

import time
time.gmtime(0)

gmtime function

When no argument is passed, it returns the current time in UTC, regardless of which time zone you are in.

time.gmtime()

gmtime function

The interesting feature to note is that the returned value is a struct_time object. This is a named tuple that is constructed using the NamedTuple class.

You can find this class in Python’s collections module. It provides a more readable and manageable interface to work with time values.

 

Get Unix timestamp

Unix timestamp is the epoch time for Unix-based operating systems. It is the number of seconds that have passed since 1 January 1970 (the Unix epoch).

To get the Unix timestamp for the current time, you can use the time() function.

from time import time
time()

time function

 

Convert string into datetime

Sometimes you may deal with situations where the user enters the datetime in a string format. You can convert this into a struct_time object using the strptime() function.

It takes 2 arguments as input. The first should be a string (a timestamp). The second argument is optional and used to specify the format of your string.

We will look into time formats in more detail in the next subsection.

from time import strptime
strptime('2022-01-12', '%Y-%m-%d')    

time strptime function

While working with the struct_time object is useful in many situations, there are other options too.

For instance, Python has a datetime module that provides some convenient functions for converting dates and times to and from strings.

It also includes the strptime() function that converts a string into date and time, but with more flexibility.

Time format

Learning how to convert a string into datetime using various formats is useful in many situations. The datetime module makes this super easy. To import this module, you need to run the following import statement.

import datetime

You can specify any string format using format specifiers and it will parse it accordingly. There are many more format codes available in Python.

Some of the most commonly used are provided below:

  • %a: abbreviated weekday eg. Sun, Mon, Tues
  • %A: full weekday eg. Sunday, Monday, Tuesday
  • %d: date of the month eg. 01, 02, 03
  • %b: abbreviated month eg. Jan, Feb, Mar
  • %m: month eg. 01, 02, 03
  • %y: year without century eg. 99, 00, 01
  • %Y: year with century eg.1999, 2000, 2001
  • %H: hour in 24-hour clock eg. 23, 00, 01
  • %M: minute eg. 00, 01, 02
  • ​​%S: second eg. 00, 01, 02

Using the format codes, you can retrieve a date in any format using the datetime module’s strptime() function.

date_string = "01-10-2021 15:30:00"
format_string = "%m-%d-%Y %H:%M:%S"
from datetime import datetime
datetime.strptime(date_string, format_string)   

datetime strptime function

 

Convert time to string

Besides converting a timestamp that is a string into a struct_time instance, you can also perform the reverse operation, i.e. convert a struct_time instance to a string.

This is useful when you want to provide the users with a more readable representation of the time.

Python’s time module includes two functions that convert a struct_time instance to a string. The first is the asctime() function which takes a tuple as an argument.

The second is the strftime() function. The latter lets you format your strings in a specific timestamp.

You can use asctime() to convert a struct_time instance to a timestamp. This function works similarly to ctime(). We saw earlier that the ctime() function takes a floating point number as an argument.

When using asctime(), you pass a tuple. Other than that, the second argument is the timestamp format.

You can optionally pass an argument to asctime() which should be a struct_time object. For that, you can use either gmtime() in case of UTC, or localtime() in case of local time representation.

The localtime() function is explained in more detail in the next section.

import time
print(time.asctime(time.gmtime()))
print(time.asctime(time.localtime()))

date to string function

If, instead of passing a struct_time object as an argument, you want to pass the time in seconds, the ctime() functions should be used.

from time import time, ctime
seconds_time = time()
ctime(seconds_time)

date to string using ctime

With asctime() function, you do not have much flexibility to format your timestamps. The strftime() is a better choice when you want to format your strings in a specific timestamp.

Just like asctime(), the strftime() function takes a struct_time object as an argument.

Additionally, you pass a format as a string that specifies the order of the elements of the time. %y specifies the year, %m specifies the month, and %d specifies the date.

import time
time.strftime('%Y-%m-%d', time.gmtime())

date to string using strftime

 

Get time for any timezone

Python’s time module has a function localtime() that returns the local time according to your time zone. The signature is similar to the gmtime() function.

You pass the number of seconds that have elapsed since the epoch and it uses this to calculate the time according to your time zone. When no argument is passed, it returns the current local time.

import time
current_local_time = time.localtime()
type(current_local_time)

struct_time function

The returned object is a struct_time type that stores various attributes which you can access using the attribute’s name.

For now, what we’re interested in is the tm_zone and tm_gmtoff attributes. tm_zone determines the time zone of your region. tm_gmtoff holds the offset that is used to calculate the current local time in seconds from the UTC time.

current_local_time = time.localtime()
current_local_time.tm_zone
current_local_time.tm_gmtoff

struct_time function attributes

However, if you want to get the time zone of any region, this module does not provide an easy way to do that. Instead, you can use a third-party module. The dateutil or pytz module are good options.

To install the dateutil package, run the following command:

pip install python-dateutil

The dateutil package includes an interface that lets you work with time zones. It uses the IANA time zone database at the backend.

The module contains a tz class that represents the information for all time zones and daylight saving time. You can get the time for any time zone using the gettz() function from this class.

To work with the dateutil package, the datetime module is a better choice rather than the time module. datetime module contains a function now() that returns the current time.

You can specify the time zone in its arguments by passing tz object with the specified time zone.

Here’s an example:

import datetime 
from dateutil import tz
London = tz.gettz("Europe/London")
London_time = datetime.datetime.now(tz = London)
London_time

time zones using dateutil

 

Measure execution time (profiling)

An extremely useful application of Python’s time module is program profiling. Program profiling (or code profiling) is a technique used in software engineering to analyze a program dynamically and measure the space and time complexity.

You can measure the execution time and performance of a program by running a counter that measures short distances of time.

Python’s time module has a function perf_counter() that does this precisely. To use this function, you need to call it twice- one before the execution of your code, and next after the code has been executed.

The value returned by perf_counter() is a measure of time from some moment.

The returned value isn’t useful on its own. To measure the actual running time, you can calculate the difference between the first returned value and the second.

Let’s see this in action.

from time import perf_counter
def my_function():
    for i in range(100):
        for j in range(100):
            continue
timer_start = perf_counter()
my_function()
timer_end = perf_counter()
execution = timer_end - timer_start
print("Execution Time: ", execution)

Code profilig using perf_counter

 

Run function at a specific time

Python’s time module can be used to run functions at specific times. Doing so lets you automate tasks and schedule scripts to run at certain time periods of the day.

To schedule a task, we can make use of the event schedule library named sched. Import the library by running the import statement.

import sched, time
def my_action():
	print("Do something")
current_time = time.ctime()
my_sched = sched.scheduler(time.localtime, time.sleep)
my_sched.enterabs(time.strptime(current_time), 0, my_action)
my_sched.run()

schedule function for specific time

 

Create a timer

A timer counts down the amount of time expended during a certain period in time (when the timer reaches zero). This is helpful in many real life situations.

You can build a program that stops a rice cooker as the timer reaches zero. Or, a timer can be used to display the remaining time in a football match. There are endless applications of a timer.

Now that you are well-versed in Python’s time functions, you can create your own timer! We will start by importing two modules that we have looked at previously: time and datetime.

The datetime module has a neat function named timedelta(). It calculates the differences in dates and times. We will also use the sleep() function to delay the program every one second.

The sleep() function will suspend the thread’s execution every 1 second. This will be used to track the seconds.

Here’s how you create your own timer.

import time
import datetime
def timer(hours, minutes, seconds):
    total_seconds = hours * 3600 + minutes * 60 + seconds
    while total_seconds > 0:
            countdown = datetime.timedelta(seconds = total_seconds)
            time.sleep(1)
            total_seconds -= 1
    print("Countdown to 0 seconds!")
hours = input("Hours: ")
minutes = input("Minutes: ")
seconds = input("Seconds: ")
timer(int(hours), int(minutes), int(seconds))

Python timer

 

Create a stopwatch (Measure Elapsed Time)

A stopwatch is a timer that measures the elapsed time by counting upwards from zero. Python’s time module makes it super easy to create your own stopwatch. Here’s how you do it.

import time
def stopwatch(seconds):
    minutes = int(seconds // 60)
    seconds = int(seconds % 60)
    hours = int(minutes // 60)
    minutes = minutes % 60
    print(f"Time: {hours}:{minutes}:{seconds}")
input("Hit enter to start the stopwatch")
start = time.time()
input("Hit enter to stop the stopwatch")
end = time.time()
elapsed_time = end - start
    stopwatch(elapsed_time)

Python Stopwatch

Leave a Reply

Your email address will not be published. Required fields are marked *