This is Day 18 of the #100DaysOfPython challenge.
This post will use the
time module from Python's standard library to explore how we can work with different time capabilities such as getting the local time and sleeping within a program.
All of the code used in this post can be found in my GitHub repository.
Let’s create the
hello-python-time-module directory and install Pillow.
At this stage, we are ready to explore using the
time module using
To do so, run
pipenv run ipython from the command line to open up the REPL.
Importing the module
First off, we will want to import the
time module. We can do so from within the REPL with the following:
Once imported, we can check that we have access to the
time module by checking the
__name__ attribute and playing around with a few methods.
time that we called on the module returns the time in seconds since the epoch as a floating point number.
On most systems, the epoch is January 1st, 1970 at midnight. This is currently referred to as Unix time.
Getting the local time
We can also use the time module to get the local or GM time, as well as format the time to a more readable format.
Formatting and parsing
We can use the time module to set a timer and sleep for a certain amount of time.
This can be useful when looping through intervals based on conditional logic.
We can use the
datetime module to compare times by converting
time objects to
We need to do so with the
Today’s post demonstrates some usages of the
time module from Python's standard library.
We covered a number of the standard methods and finished with an example on how to compare using the
Resources and further reading
- The ABCs of Pipenv
- Datetime In Python
- Series: Working with dates and times in Python
- GitHub repository with final code
Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.