avatarFahadul Shadhin

Summary

The provided content offers a comprehensive guide to using the time module in Python for representing, converting, and manipulating time.

Abstract

The article delves into the functionalities of the Python time module, explaining how to work with time in various formats. It covers the representation of time as a floating-point number, conversion to strings, manipulation as tuples and objects, and the use of time in calculations and formatting. The tutorial also demonstrates how to use the time module to pause code execution with time.sleep(), and it provides practical examples to illustrate the concepts discussed. The content is designed to help Python programmers understand and utilize the time module effectively in their projects.

Opinions

  • The time module is considered essential for time-related operations in Python, with the ability to represent time in multiple ways.
  • The author emphasizes the importance of understanding the epoch as the starting point for time calculations in the time module.
  • The article suggests that representing time as a floating-point number simplifies calculations, such as finding time differences.
  • The use of time.ctime() and time.strftime() is recommended for creating human-readable time representations.
  • The author highlights the flexibility of time.strftime() for custom timestamp formatting.
  • The time.sleep() function is presented as particularly useful for controlling the execution pace of a program, implementing delays, and creating countdowns.
  • The article concludes by encouraging readers to explore the time module further to discover additional functions and use cases, implying that the module has more to offer beyond the basics covered in the article.

How To Use the Time Module in Python

Representation, conversion, and manipulation of time using the Python time module

Photo by Ylanite Koppens from Pexels

The time module in Python provides many functionalities to represent and work with time in our code. We can represent time in different formats, convert time from one format to another, use time in our code as per the need using the time module.

In this article, you will get a proper understanding of how to work with time in Python using the time module.

Table of Contents:
· Python Time in Seconds as a Floating-Point Number
· Time in Seconds to a String
· The Time Tuple
· Python Time as an Object
· Floating-Point Time in Seconds to an Object
  ∘ UTC TimeLocal Time
· Time Object to a String
  ∘ Using asctime()
  ∘ Using strftime()
· Python Time String to an Object
· time.sleep()
· References

Python Time in Seconds as a Floating-Point Number

The basic representation of time in the time module is a floating-point number in seconds. time.time() will give you the current time in seconds. But first, you need to import the time module.

>>> import time
>>> time.time()
1633525484.7117667

time.time() returns a floating-point number of seconds that have passed since a starting point of time. The starting point of time is called the epoch.

The epoch is the point where the time starts and is platform-dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). To find out what the epoch is on a given platform, look at time.gmtime(0)Python documentaion

You can find the epoch for your platform using time.gmtime(0)

>>> import time
>>> time.gmtime(0)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

This is another representation of time as an object. It will be discussed later in this article. For now, we are just using it to find the epoch.

By representing time as a floating-point number you can easily use it in your code. The calculation becomes easy this way. Suppose you want to calculate the time difference of two points in your code. You just need to subtract the time values of two points.

time_diff.py does some basic calculation in a for a loop. Using the floating-point representation of time in this code we are easily calculating the time difference between two states.

Time in Seconds to a String

Using time.ctime() you can convert a time represented in seconds elapsed from the epoch to a string.

>>> import time
>>> current_time = time.time()
>>> timestamp = time.ctime(current_time)
>>> print(timestamp)
Wed Oct 6 19:42:04 2021

This string representation of time is also known as a timestamp. time.ctime() returns the string representation of time in the following format:

  • The day of the week (Wed)
  • The month of the year (Oct)
  • The day of the month (6)
  • Hours, minutes, and seconds (19:42:04)
  • The year (2021)

This is a more human-readable representation of time. time.ctime() returns the local time which depends on your geometrical location.

The Time Tuple

If you want you can represent the previous timestamp as a tuple or list. Every element of the time tuple represents a specific element of time. the sequence goes like this:

  • Year
  • Month (as an integer between 1(January) and 12(December))
  • Day of the month
  • Hour (as an integer between 0(12 A.M.) and 23(11 P.M.))
  • Minute
  • Second
  • Day of the week (as an integer between 0(Monday) and 6(Sunday))
  • Day of the year
  • Daylight savings time (1 for daylight saving time, 0 for standard time, -1 for unknown)

So, a time tuple will be something like this —

>>> time_tuple = (2021, 10, 6, 19, 42, 4, 2, 59, 0)

Python Time as an Object

The reason you may want to represent time as a sequence is that using this sequence representation you can convert the time into an object. For this, you will use time.struct_time().

>>> import time
>>> time_tuple = (2021, 10, 6, 19, 42, 4, 2, 59, 0)
>>> time.struct_time(time_tuple)
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=19, tm_min=42, tm_sec=4, tm_wday=2, tm_yday=59, tm_isdst=0)

This gives you the ability to access specific elements of the time object easily.

>>> time_obj = time.struct_time(time_tuple)
>>> time_obj.tm_yday
59
>>> time_obj.tm_hour
19
>>> time_obj.tm_year
2021
>>> time_obj.tm_mday
6

Floating-Point Time in Seconds to an Object

The epoch used UTC for its definition. Therefore, the representation of time in seconds elapsed since the epoch is also in UTC. But you can convert a floating-point representation of time to an object in two ways:

  1. UTC
  2. Local time

UTC Time

To convert a floating-point time to a UTC-based object you will use time.gmtime(). We used time.gmtime(0) to find the epoch previously. Actually time.gmtime() converts the floating-point time elapsed from epoch to a struct_time object. time.gmtime() will return the current time as an object.

>>> import time
>>> time.gmtime()
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=14, tm_min=28, tm_sec=2, tm_wday=2, tm_yday=279, tm_isdst=0)

Using time.gmtime() floating-point time is easily converted to an object. But the other way around is a little complicated. To convert a struct_time to a floating-point time you need to first import the calendar module. Then you need to use calendar.timegm().

>>> import time
>>> import calendar
>>> time_obj = time.gmtime()
>>> calendar.timegm(time_obj)
1633531197

If you want the time object after a certain time from the epoch, you need to send the elapsed time in seconds as a parameter in time.gmtime(). Suppose you want the time object one year after the epoch. One year = 60 * 60 * 24 * 365 = 31536000 seconds. You need to put that in time.gmtime() as an argument.

>>> import time
>>> epoch = time.gmtime(0)
>>> epoch
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> elapsed_time = 60 * 60 * 24 * 365
>>> time.gmtime(elapsed_time)
time.struct_time(tm_year=1971, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=1, tm_isdst=0)

Look at the tm_year. It is one year after the epoch.

Local Time

To convert a floating-point time in seconds to a time object in local time, you need to use time.localtime().

>>> import time
>>> time.time()
1633531695.5643973
>>> time.localtime(time.time())
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=20, tm_min=48, tm_sec=27, tm_wday=2, tm_yday=279, tm_isdst=0)

You can also check the time zone using tm_zone.

>>> time.localtime(time.time()).tm_zone
‘+06

To convert a local time object back to a floating-point time in seconds you just need to use time.mktime().

>>> import time
>>> time_obj = time.localtime(time.time())
>>> time.mktime(time_obj)
1633532173.0

Time Object to a String

Using asctime()

Using asctime() you can convert both gmtime() and localtime() to a string timestamp.

>>> import time
>>> time.asctime(time.gmtime())
‘Wed Oct 6 15:06:37 2021’
>>> time.asctime(time.localtime())
‘Wed Oct 6 21:06:44 2021

Using strftime()

asctime() doesn’t give you the flexibility to format timestamp as per your need. But using time.strftime() you can format time in a more meaningful way for your use. time.strftime() takes two arguments:

  1. The format of time elements of the timestamp string
  2. time tuple (optional)

Here is the full chart for formatting a timestamp in strftime():

The screenshot is taken from the Python documentation

Here is an example of using time.strftime()

>>> import time
>>> time_obj = time.localtime()
>>> time.strftime(‘%Y-%m-%d’, time_obj)
‘2021–10–06’

Python Time String to an Object

Using time.strptime() you can convert a string timestamp to a time object. strptime() takes two arguments —

  1. The string timestamp
  2. format (optional)
>>> import time
>>> time.strptime(‘2021–10–06’, ‘%Y-%m-%d’)
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=279, tm_isdst=-1)

The format is optional and defaults to the format %a %b %d %H:%M:%S %Y. So if you have a timestamp in this format, you don’t need to provide the second argument.

>>> import time
>>> time.strptime(‘Wed Oct 6 19:42:04 2021’)
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=19, tm_min=42, tm_sec=4, tm_wday=2, tm_yday=279, tm_isdst=-1)

time.sleep()

time.sleep() function demands its own section because it is really useful and commonly used in programs. Using time.sleep() you can suspend the execution of your code for a certain amount of time.

>>> import time
>>> time.ctime()
'Wed Oct  6 21:37:40 2021'
>>> time.sleep(10)
>>> time.ctime()
'Wed Oct  6 21:37:50 2021'

Here the execution of the code is suspended for 10 seconds. You can also use a fractional value of seconds in time.sleep().

>>> time.sleep(0.7)

Here your code will sleep for 0.7 seconds.

time.sleep() is really handy when you need to make your code wait for a certain amount of time. It is also useful to implement a countdown.

Here is a basic implementation of a 10 seconds countdown:

Conclusion

In this article, I gave you a brief overview of the Python time module. I hope this helps you to build a proper foundation for working with time in Python. And hopefully, you will discover other functions and use cases of the time module as you continue to use and explore it.

Thanks for reading. If you want to learn about Python modules and packages, you may find the article below helpful for you:

References

Programming
Python
Software Development
Data Science
Machine Learning
Recommended from ReadMedium