Timing Functions in Python

time library link to docs
timeit library link to docs


In [1]:
import time
import timeit

UTC and local time

time has methods which return the UTC time and local time in a somewhat useless structure format.
time.gmtime() returns the structure with the current gm or UTC time.
time.localtime() returns a structure with the current local time


In [2]:
currentTime = time.gmtime()
print(currentTime)


time.struct_time(tm_year=2017, tm_mon=4, tm_mday=23, tm_hour=2, tm_min=4, tm_sec=19, tm_wday=6, tm_yday=113, tm_isdst=0)

As you can see, the returned values are not very interesting or useful themselves. Lets parse structure into more useful forms.

First, lets parse it into a human-readable form. This is useful for printing the time to the console, but generally would be used with a secondary form that is easier for a computer to read.


In [3]:
time.strftime("%a, %d %b %Y %H:%M:%S +0000", currentTime)


Out[3]:
'Sun, 23 Apr 2017 02:04:19 +0000'

Now lets parse it into a computer-friendly form. To start with, we should understand what type of structure currentTime is.


In [4]:
type(currentTime)


Out[4]:
time.struct_time

As we can see, currentTime is an instance of a class, struct_time as is defined in the time library.

The string that was returned when we ran print(currentTime) showed us the values associated with several of the class variables. We can access these class variables by using the dot "." notation.


In [5]:
currentTime.tm_hour


Out[5]:
2

With this knowledge, it becomes trivial to parse this data into a more usable format.


In [6]:
def parseTime(timeObj):
    '''parseTime:
    takes time.struct_time instances
    :return  time displayed as string -  year month day hour min sec'''
    return (str(timeObj.tm_year) + str(timeObj.tm_mon) + str(timeObj.tm_mday) +
            str(timeObj.tm_hour) + str(timeObj.tm_min) + str(timeObj.tm_sec))

In [7]:
parseTime(currentTime)


Out[7]:
'20174232419'