time
library link to docs
timeit
library link to docs
In [1]:
import time
import timeit
In [2]:
currentTime = time.gmtime()
print(currentTime)
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]:
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]:
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]:
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]: