Having looked at the Python
datetime modules in previous articles, today we’ll take a closer look at the
time module and understand how to extract, input, and work with times in our coding. First, I’ll recap on computer time and introduce the time object we’ll be using with the functions we introduce later in the article. Then we’ll explore the most important functions within the
time module and do some work specifically with the
time.struct_time() class, creating and extracting information.
How Computers Measure Time
Most computer systems use a system of timekeeping called Unix Time, or Epoch Time, and count seconds from the Unix Epoch, which is arbitrarily set at 00:00:00 UTC on 1 January 1970. UTC stands for Coordinated Universal Time which is the time at 0 degrees longitude.
Within Python, we can find out the current number of seconds since Epoch Time by importing the time module and using the class
time(), as shown here.
import time z = time.time() print(z) # Result # 1621591198.1681073
This Epoch time number forms the basis of any further time calculations we may do within the time module. With that clear, let’s look at the Python time object created by some of the classes we will shortly introduce.
If you need a quick refresher on Python classes, check out the Finxter Academy course on object-oriented programming that will give you a deep dive into concepts, theory, and technical understanding of objects and classes.
Introducing the struct_time Class
time.struct_time class is a Python object consisting of a time value sequence which is returned by a number of the functions we will shortly introduce. The object takes the form of a named tuple. If you haven’t come across a named tuple before, it is a tuple with distinct names applied to the values. This allows you to call the values by attribute name rather than index. Here’s a quick example of defining a named tuple and then printing an item using its attribute
from collections import namedtuple z = time.time() print(z) count = namedtuple('count', 'a, b, c, d') z = count(a='ten', b='six', c='five', d='two') print(z.c) # Calling content by name print(z) # Calling content by index # Result: # five # five
You can still retrieve an item by index with a named tuple, as shown by the last print command.
time.struct_time class uses the following attribute names:
|Tuple Index Position||Attribute Name||Possible Values|
|0||tm_year||(for example, 1993)|
|1||tm_mon||range [1, 12]|
|2||tm_mday||range [1, 31]|
|3||tm_hour||range [0, 23]|
|4||tm_min||range [0, 59]|
|5||tm_sec||range [0, 61]|
|6||tm_wday||range [0, 6], Monday is 0|
|7||tm_yday||range [1, 366]|
|8||tm_isdst||0, 1 or -1; see below|
|N/A||tm_zone||abbreviation of timezone name|
|N/A||tm_gmtoff||offset east of UTC in seconds|
You’ll see this structure in use very shortly in our coding examples.
Master the Most Useful Time Functions
I will run through a number of the main functions in the time module and show you examples of each when used in code. You’ve already been introduced to
time.time() in the discussion above about Epoch Time. This function returns the UTC time in seconds since 1 January 1970. Here are a few more useful functions.
There is also the function
time_ns() which returns Epoch time but in nanoseconds for a greater level of precision. Here’s some code comparing a
time.time() call against a
time.time_ns() call. Remember to
import time for all of these code examples.
import time a = time.time() b = time.time_ns() print(a) print(b) # Result 1621594866.7063224 # Epoch time 1621594866706322500 # Nano second Epoch
This function converts a time, expressed in seconds since the epoch, to the
struct_time format in UTC. If no seconds are entered into the function, it will return the current time returned by
time(). I’ll introduce another function, and then we’ll run some code for both.
This function converts a time, expressed in seconds since the epoch, to the struct_time format in UTC. If no seconds are entered into the function, it will return the current time returned by
time(). I’ll introduce another function, and then we’ll run some code for both.
localtime() is similar to
gmtime() but converts the epoch time to a
struct_time format in local time. If no seconds are entered into the function, it will return the current time returned by
time(). Let’s run some code for both functions, and you’ll see the struct_time layout returned, as previously described.
c = time.gmtime() d = time.localtime() print('Epoch as struct_time Tuple - UTC: ', c) print('Epoch as struct_time Tuple - Local: ', d) # Result Epoch as struct_time Tuple - UTC: time.struct_time(tm_year=2021, tm_mon=5, tm_mday=21, tm_hour=12, tm_min=28, tm_sec=55, tm_wday=4, tm_yday=141, tm_isdst=0) Epoch as struct_time Tuple - Local: time.struct_time(tm_year=2021, tm_mon=5, tm_mday=21, tm_hour=13, tm_min=28, tm_sec=55, tm_wday=4, tm_yday=141, tm_isdst=1)
You can plainly see the named tuple result. The first is the
struct_time object in UTC showing a date of 21 May 2021 and a time of 12:28:55, and the second is the
struct_time object in local time, which in this case is British Summer Time, which is one hour ahead of UTC and showing 21 May 2021 at 13:28:55.
It’s worth noting the
tm_wday attribute, which refers to a value of 4. The table above shows attribute names and possible values. 0 refers to a Monday; therefore, 4 refers to a Friday, correct for 21 May 2021.
This function does the opposite of
localtime(). It requires either a struct_time object or a tuple with all 9 attributes supplied. The
time_struct object is passed to variable d in the above code. Let’s use
mktime() to convert variable
d back to epoch time. Then we’ll pass a 9 attribute tuple to
mktime() to return the epoch time for that date.
e = time.mktime(d) y = (2022, 3, 15, 9, 17, 26, 1, 0, 0) z = time.mktime(y) print(e) print(z) # Result 1621601639.0 # Epoch time for e 1647335846.0 # Epoch time for z
Note that it will return UTC because I used a 0 in the last attribute in the tuple. If I’d put -1, it meant I didn’t know the timezone or didn’t care, in which case
mktime() will return local Epoch time.
This function converts an epoch time to a string with a specific format,
‘Mon Apr 26 18:32:43 2021’. We’ll run
ctime() on the two variables
z above to return their respective formatted strings.
e = time.mktime(d) y = (2022, 3, 15, 9, 17, 26, 1, 0, 0) z = time.mktime(y) print(e) print(z) print(time.ctime(e)) print(time.ctime(z)) # Result 1621602193.0 # Epoch time for e 1647335846.0 # Epoch time for z Fri May 21 14:03:13 2021 # Returned string for e Tue Mar 15 09:17:26 2022 # Returned string for z
The last two functions I wish to introduce are converting a
struct_time object to a string that may be formatted by us, or converting a string to a
strftime() takes either a struct_time object or a 9 attribute tuple and converts it to a string whose format we can dictate by codes. The complete list of available codes may be found here, but I’ll use the following:
- %a = the locales abbreviated weekday name, e.g., Mon for Monday
- %b = the day of the month as a decimal number from 1 to 31
- %d = the locales abbreviated month name, e.g., Feb for February
- %Y = the year with the century as a decimal number, e.g., 2021
- %H = Hour in the 24-hour clock as a decimal number from 1 to 23
- %M = Minutes as a decimal number from 00 to 59
- %S = Seconds as a decimal number from 00 to 61
The two arguments taken by
strftime() must be the format string followed by either the
struct_time object or a 9 attribute tuple.
import time a = time.gmtime() b = time.localtime() print(time.strftime('%a, %d %b %Y %H:%M:%S GMT', a)) print(time.strftime('%a, %d %b %Y %H:%M:%S BST', b)) # Result Fri, 21 May 2021 13:25:38 GMT Fri, 21 May 2021 14:25:38 BST
strptime() returns a
struct_time object from a date string, followed by the format of the string. We’ll convert a date string to a
struct_time object in the following code then we’ll retrieve some data by calling the individual attributes.
z = time.strptime('21 May 15 16 59 34', '%d %b %y %H %M %S') print(z, '\n') print(z.tm_year, '\n') print(z.tm_mday, z.tm_mon, z.tm_year) # Result time.struct_time(tm_year=2015, tm_mon=5, tm_mday=21, tm_hour=16, tm_min=59, tm_sec=34, tm_wday=3, tm_yday=141, tm_isdst=-1) 2015 21 5 2015
In this article, we took a look at the time module in Python. We discussed Epoch Time using
time_ns() to return the number of seconds since 1 January 1970 in UTC. We then introduced the time module class
struct_time, which takes the form of a named tuple.
We discussed how named tuples are created and used and looked at the attributes used by the
We then introduced six useful functions of the time module. We created
time_struct objects using
mktime(), we used a 9 digit tuple to return an epoch time in seconds and
ctime() to take an epoch time and return a specifically formatted time.
Finally, we used
strftime() to take a
struct_time object, or a 9 attribute tuple, and convert it to a string whose format we can dictate. Then we used
strptime() to take a string and return it as a
struct_time object, recalling specific values by calling the object’s attributes.
I trust this article was helpful, and I encourage you to visit python.org to investigate the many other functions available for use. Thanks for reading.
David is a Python programmer and a technical writer creating in-depth articles for readers wanting uncomplicated explanations for topics made difficult by industry jargon. Also a woodworker, metalworker, landscape photographer, and pilot, he is freelance after 42 years in the corporate world. He has an MBA in Technology.