What Can You Do With Python’s Time Module?
You can write programs that launch other programs on a schedule by using the subprocess and threading modules.
For example, you could schedule a backup for every week or month and at a scheduled time like 10: 00 pm.
Alright, before we get started I’d like to give a glimpse of what this article covers.
- The Time Module
- Suspending execution — time.sleep() Function
- understanding time zones
- Creating a StopWatch-Project
The Time Module
Your computer’s system clock is set to a specific date, time, and time zone.
The built-in time module allows your Python programs to read the system
clock for the current time. The time.time() and time.sleep() functions are
the most useful in the time module.
The time.time() Function
The Unix epoch is a time reference commonly used in programming: 12 am
on January 1, 1970, Coordinated Universal Time (UTC).More about time will be exaggerated later in the 3rd section of this article.For now let us look at
The time.time()
function returns the number of seconds since that moment as a float value.
This number is called an epoch timestamp. For example, enter the following into the interactive shell:
Here , I’m running this on 4th October, 2020 15:59 IST
How do you get the execution time of a piece of code ?
Let’s say I have a function and I want to calculate the factorial of a very large number. Of Course , you can solve this problem using recursion but that is out of the scope of this article
For the first execution I ran it with n=100000 and it gave me the output as above . For the second time I ran it with n=10⁷ and it haven’t calculated the answer yet : )
Suspending execution — time.sleep() Function
One really useful Python time function is sleep()
, which suspends the thread’s execution for a specified amount of time. Pass it the number of seconds you want your program to stay paused.
For Example ,
You might notice the time difference of 1 sec while printing the content .
It goes, tick..tock,tick..tock ,tick..tock !
Before Python 3.5, a signal sent to your process could interrupt sleep()
. However, in 3.5 and later, sleep()
will always suspend execution for at least the amount of specified time, even if the process receives a signal.
sleep()
is just one Python time function that can help you test your programs and make them more robust.
Understanding time zones
UTC is the time standard against which all the world’s timekeeping is synchronized (or coordinated). It is not, itself, a time zone but rather a transcendent standard that defines what time zones are.
UTC time is precisely measured using astronomical time referring to the Earth’s rotation, and atomic clocks.
Time zones are then defined by their offset from UTC. For example, in North and South America, the Central Time Zone (CT) is behind UTC by five or six hours and, therefore, uses the notation UTC-5:00 or UTC-6:00.
There are two ways to convert a float representing seconds to a struct_time
:
- UTC
- Local time
To convert a Python time float to a UTC-based struct_time
, the Python time
module provides a function called gmtime()
.You can use time.gmtime()
to determine your system’s epoch:
While January 1, 1970 UTC is a common epoch, it is not the only epoch used in computing. In fact, different operating systems, filesystems, and APIs sometimes use different epochs.
As you saw before, UNIX systems define the epoch as January 1, 1970. The Win32 API, on the other hand, defines the epoch as January 1, 1601.
>>> 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)
There are two Python time functions that you use for converting a time.struct_time
object to a string:
asctime()
Both gmtime()
and localtime()
return struct_time
instances, for UTC and local time respectively.
You can use asctime()
to convert either struct_time
to a timestamp. asctime()
works similarly to ctime()
, which you learned about earlier in this article, except instead of passing a floating point number, you pass a tuple. Even the timestamp format is the same between the two functions.
2.strftime()
This function provides you the flexibility to print the data as per your format , whether american or british or Japanese.
For example,
Project- Stop Watch.
Say you want to track how much time you spend on boring tasks you haven’t
automated yet. You don’t have a physical stopwatch, and it’s surprisingly dif-
ficult to find a free stopwatch app for your laptop or smartphone that isn’t
covered in ads and doesn’t send a copy of your browser history to marketers.
(It says it can do this in the license agreement you agreed to. You did read
the license agreement, didn’t you?) You can write a simple stopwatch pro-
gram yourself in Python.
At a high level, here’s what your program will do:
1) Track the amount of time elapsed between presses of the enter key,
with each key press starting a new “lap” on the timer.
2) Print the lap number, total time, and lap time.
This means your code will need to do the following:
1) Find the current time by calling time.time() and store it as a timestamp
at the start of the program, as well as at the start of each lap.
2) Keep a lap counter and increment it every time the user presses enter .
3) Calculate the elapsed time by subtracting timestamps.
4) Handle the KeyboardInterrupt exception so the user can press ctrl -C
to quit.
Now , let us talk about the components of our program.
Step1
print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch.
Press Ctrl-C to quit.')
input()
I am running my program on ubuntu 20.04 lts and via terminal.The input which is ENTER in this case is pressed and the programs booms
startTime = time.time()
# get the first lap's start time
lastTime = startTime
lapNum = 1
The current time when the program runs is took into a variable called ‘startTime’ . The variable ‘lapNum’ is initialised with 1
step2 — Track and print lap times
We’ll display the lap time and total time and increase the lap count
for each new lap. The total time is from when the program was first started
- So here , I start my program by keyboard input ENTER.
- First lap records of 5.27 secs, second lap 57.73 secs and so on
- and when I want to terminate my program , I terminate it using keyboard interrupt which is ctrl+C .
You can always refer the source code but before that you should give it a try !
: )
Resources and acknowledgements:-
Automate the boring stuff in Python
Thank You !