Python's Time Module is here to save the day!
In this post, we'll explore how to use the Time Module and its various applications.
You can use the various functions in the Time Module to parse and format time-sensitive data, such as stock market data or weather forecasts.
π How to import Time Module in Python?
First things first, let's import the Time Module. The time module comes with Pythonβs standard utility module, so there is no need to install it externally.
import time
π What is epoch?
time.gmtime(0) Function in Python
Epoch is the point where the time starts and is platform-dependent.
For Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC), and leap seconds are not counted towards the time in seconds since the epoch.
To check the epoch of a given platform, we can useΒ time.gmtime(0)
import time
print(time.gmtime(0))
Output:
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)
The time before the epoch can still be represented in seconds but it will be negative. For example, 31 December 1969 will be represented as -86400 seconds
π How to get the current time in seconds since epoch?
time() Function in Python
The time()
function returns the current system time in seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). You can use the time() function to benchmark the performance of your code and identify areas that need optimization.
from time import time
time = time()
print(time)
Output:
1679730367.4577837
You can use the time() function to set specific times for tasks to run
π How to get time in string from seconds?
time.ctime() Function in Python
The function time.ctime()
returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If secs is not provided or None, the current time as returned by time() is used. It can be used to get the date, time and day of the week.
import time
timeNow = time.ctime(1679724175.2855277)
print("Current Date, Time:", timeNow)
Output:
Current Date, Time: Sat Mar 25 11:32:55 2023
π How to calculate execution/running time of a Python Program?
We can determine the elapsed time by recording the time just before the algorithm and the time just after the algorithm, and computing their difference.
from time import time
startTime = time() # record the starting time
# run algorithm
endTime = time() # record the ending time
elapsed = endTime β startTime # compute the elapsed time
π How to delay execution of a python program?
sleep() Function in Python
The sleep()
function suspends the execution of the current thread for a specified number of seconds. It's a great way to add delays in your code, whether it's for animation or to prevent overloading a server.
import time
print("This message will appear immediately")
time.sleep(5)
print("This message will appear 5 seconds later")
import time
for i in range(5):
time.sleep(i)
print(i) # Each number i will be printed after i seconds
π How to converts a tuple representing a time as returned by gmtime()
to a specific format?
time.strftime() function in Python
time.strftime()
function converts a tuple representing a time as returned by gmtime()
or localtime()
to a string as specified by the format argument. If t(time in number of seconds to be formatted ) is not provided, the current time as returned by localtime()
is used. The format must be a string. ValueError is raised if any field in t is outside of the allowed range.
from time import gmtime, strftime
# using simple format of showing time
s = strftime("%a, %d %b %Y %H:%M:%S + 1010", gmtime())
print("Example 1:", s)
print()
# only change in this is the full names
# and the representation
s = strftime("%A, %D %B %Y %H:%M:%S + 0000", gmtime())
print("Example 2:", s)
print()
# this will show you the preferred date time format
s = strftime("%c")
print("Example 3:", s)
print()
# this will tell about the centuries
s = strftime("%C")
print("Example 4:", s)
print()
# % R - time in 24 hour notation
s = strftime(" %R ")
print("Example 5:", s)
print()
# % H - hour, using a 24-hour clock (00 to 23) in Example 1, 2, 3
# % I - hour, using a 12-hour clock (01 to 12)
s = strftime("%a, %d %b %Y %I:%M:%S + 0000", gmtime())
print("Example 6:", s)
print()
# % T - current time, equal to % H:% M:% S
s = strftime("%r, %T ", gmtime())
print("Example 7:", s)
print()
# % u an % U use (see difference)
s = strftime("%r, %u, %U")
print("Example 8:", s)
print()
# use of % V, % W, % w
s = strftime("%r, %V, %W, %w")
print("Example 9:", s)
print()
# use of % x, % X, % y, % Y
s = strftime("%x, %X, %y, %Y")
print("Example 10:", s)
print()
# use of % Z, % z
s = strftime("%r, %z, %Z")
print("Example 11:", s)
Output:
Example 1: Sat, 25 Mar 2023 09:32:00 + 1010
Example 2: Saturday, 03/25/23 March 2023 09:32:00 + 0000
Example 3: Sat Mar 25 15:02:00 2023
Example 4: 20
Example 5: 15:02
Example 6: Sat, 25 Mar 2023 09:32:00 + 0000
Example 7: 09:32:00 AM, 09:32:00
Example 8: 03:02:00 PM, 6, 12
Example 9: 03:02:00 PM, 12, 12, 6
Example 10: 03/25/23, 15:02:00, 23, 2023
Example 11: 03:02:00 PM, +0530, India Standard Time
π How Python Time module is used in Building time-based animations?
You can use the sleep()
function to add delays between animation frames, or use the time()
function to set specific frame rates.
π How to make a stopwatch using Python Time Module?
from time import time
while True:
startTime = 0
endTime = 0
elapsedTime = 0
user = input("Type s to start the STOPWATCH\nType x to stop the STOPWATCH\t").strip()
if user == "S" or user == "s":
startTime = time()
print("STOPWATCH started")
user2 = input()
if user2 == "x" or user2 == "X":
endTime = time()
elif user2 == "s" or user2 == "S":
print("STOPWATCH already started. You can stop it by typing x")
else:
print("Invalid input. Please try again.")
elapsedTime = endTime - startTime
print(f"Total time elapsed: {elapsedTime} seconds")
break
elif user == "x" or user == "X":
print("STOPWATCH not yet started. You can start it by typing s")
else:
print("Invalid input. Please try again.")
π How to implement a Pomodoro Timer using Python Time Module
import time
import os
work_time = 25 * 60
break_time = 5 * 60
long_break_time = 15 * 60
session_count = 0
def start_timer(duration, message):
for i in range(duration, 0, -1):
minutes = i // 60
seconds = i % 60
timer_display = f"{minutes:02d}:{seconds:02d}"
print(f"\r{message} ({timer_display})", end="")
time.sleep(1)
print("\nDone!")
os.system("say 'Time's up!'")
while True:
user_input = input("Press 's' to start a Pomodoro session or 'q' to quit: ")
if user_input == 's':
session_count += 1
if session_count % 4 == 0:
start_timer(long_break_time, "Long Break")
else:
start_timer(work_time, "Work")
start_timer(break_time, "Short Break")
elif user_input == 'q':
print("Goodbye!")
break
else:
print("Invalid input. Please try again.")
And we are -
Happy Coding! π
Share this with someone who would need it! π
Follow for more β‘
Top comments (2)
Share this with someone who would need it! π
Did this post help you?
Save it for later...
lets_code_together