

Photo by Editor | Chat GPT
. Introduction
Most of the developers are familiar with this time
Module, its easy tasks. Like time.sleep()
. This makes a simple but essential tool to go to hang the module. However, time
The module is far more versatile, which offers precise measurements, time changes, and formatting functions of a suit functions that are often noticed by anyone. The detection of these capabilities can open more effective ways to handle time -related tasks in your data science and other coding projects.
I’ve got some flak in the name of the last “10 amazing things” articles, and I got it. “Yes, it is surprising that I can perform the date and time work with the dattime module, thank you.” Correct criticism. However, the name is sticking because it is charming, so to deal with it 🙂
In any case, here are 10 amazing and useful things you can do with the time
Module
. 1. Measure the correctly with the time of the wall clock time.monotonic()
While you can go automatically time.time()
To measure what time it takes in a function is an important flaw in: it’s based on System ClockWhich can be changed manually or by a network time protocol. This can lead to wrong or even negative time differences. There is another strong solution time.monotonic()
. This function returns the price of a monotonic watch, which cannot be backward and is not affected by system time updates. This really makes the best choice for measuring periodic measurements.
import time
start_time = time.monotonic()
# Simulate a task
time.sleep(2)
end_time = time.monotonic()
duration = end_time - start_time
print(f"The task took {duration:.2f} seconds.")
Output:
The task took 2.01 seconds.
. 2. CPU measure the time of processing time.process_time()
Sometimes, you don’t care about the total time (wall time). Instead, you would like to know how much time the CPU has spent actually implementing your code. It is very important to be benchmarking the algorithm performance, as it ignores the time to wait for gold or I/O operations. time.process_time()
The function returns the current process system and the user’s CPU time, which provides a pure measure of computational effort.
import time
start_cpu = time.process_time()
# A CPU-intensive task
total = 0
for i in range(10_000_000):
total += i
end_cpu = time.process_time()
cpu_duration = end_cpu - start_cpu
print(f"The CPU-intensive task took {cpu_duration:.2f} CPU seconds.")
Output:
The CPU-intensive task took 0.44 CPU seconds.
. 3. Get with high precision timstamp time.perf_counter()
For the extremely exact time, especially for a very short period of time, time.perf_counter()
There is an essential tool. It returns a high resolution performance counter, which is the most accurate watch available on your system. It is counting across a system, which includes sleeping time, which makes it the best of the benchmark scenario where every nano second is counted.
import time
start_perf = time.perf_counter()
# A very short operation
_ = (x*x for x in range(1000))
end_perf = time.perf_counter()
perf_duration = end_perf - start_perf
print(f"The short operation took {perf_duration:.6f} seconds.")
Output:
The short operation took 0.000028 seconds.
. 4. Change the timstamp into a wire to read time.ctime()
Production time.time()
There is a float representing seconds after the “covenant” (January 1, 1970, for the Unix system). Although calculation is useful useful, it is unable to read human. time.ctime()
The function takes this time stamp and transforms it into a standard, easy wire format, such as ‘Thu July 16:32:30 2025’.
import time
current_timestamp = time.time()
readable_time = time.ctime(current_timestamp)
print(f"Timestamp: {current_timestamp}")
print(f"Readable Time: {readable_time}")
Output:
Timestamp: 1754044568.821037
Readable Time: Fri Aug 1 06:36:08 2025
. 5. Analyze the time from a string time.strptime()
We say that you have time information stored as a wire and need to convert it into a structural time object. time.strptime()
(String Pars Time) Your function. You provide string and a format code that explains how the date and time components are arranged. It loots a struct_time
Object, which is a topal with elements – such as year, month, day, and so on – which can be removed after.
import time
date_string = "31 July, 2025"
format_code = "%d %B, %Y"
time_struct = time.strptime(date_string, format_code)
print(f"Parsed time structure: {time_struct}")
print(f"Year: {time_struct.tm_year}, Month: {time_struct.tm_mon}")
Output:
Parsed time structure: time.struct_time(tm_year=2025, tm_mon=7, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=212, tm_isdst=-1)
Year: 2025, Month: 7
. 6. Time in Custom Dore with Format Time time.strftime()
Unlike parsing is formatting. time.strftime()
(String format time) takes struct_time
Object (such as one has returned by one strptime
Or localtime
) And it format it in the string according to its specific format code. This gives you full control over the output, whether you prefer “2025-07-31” or “Thursday, July 31”.
import time
# Get current time as a struct_time object
current_time_struct = time.localtime()
# Format it in a custom way
formatted_string = time.strftime("%Y-%m-%d %H:%M:%S", current_time_struct)
print(f"Custom formatted time: {formatted_string}")
day_of_week = time.strftime("%A", current_time_struct)
print(f"Today is {day_of_week}.")
Output:
Custom formatted time: 2025-08-01 06:41:33
Today is Friday
. 7. Get the basic time zone information time.timezone
And time.tzname
While Date Time Module (and Like Libraries Pytz) Are better for complex tim zone handling time
The module offers some basic information. time.timezone
Offset seconds in the west of the UTC provides a timelous zone offset in the local non -DST (daylight saving time), while time.tzname
There is a tuple containing local non -DST and DST Time Zone names.
import time
# Offset in seconds west of UTC
offset_seconds = time.timezone
# Timezone names (standard, daylight saving)
tz_names = time.tzname
print(f"Timezone offset: {offset_seconds / 3600} hours west of UTC")
print(f"Timezone names: {tz_names}")
Output:
Timezone offset: 5.0 hours west of UTC
Timezone names: ('EST', 'EDT')
. 8. UTC and replace with local time time.gmtime()
And time.localtime()
Working with different time zones can be difficult. One of the common customs is to preserve all time data in the integrated Universal Time (UTC) and convert it to local time just for display. time
The module provides convenience with it time.gmtime()
And time.localtime()
. These functions take time stamp in seconds and back struct_time
Objection – gmtime()
Returns it to UTC, while localtime()
Return it to the time zone of your system.
import time
timestamp = time.time()
# Convert timestamp to struct_time in UTC
utc_time = time.gmtime(timestamp)
# Convert timestamp to struct_time in local time
local_time = time.localtime(timestamp)
print(f"UTC Time: {time.strftime('%Y-%m-%d %H:%M:%S', utc_time)}")
print(f"Local Time: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)}")
Output:
UTC Time: 2025-08-01 10:47:58
Local Time: 2025-08-01 06:47:58
. 9. Perform the reversal time.time()
With time.mktime()
time.localtime()
Changes the timstamp into A struct_time
Object, which is useful … but how do you go in the opposite direction? time.mktime()
The function does it exactly. It takes a struct_time
Object (represents local time) and converts it to a floating point number representing seconds from far away. Then it is useful for calculating the future or past timestops or performing the mathematics of history.
import time
# Get current local time structure
now_struct = time.localtime()
# Create a modified time structure for one hour from now
future_struct_list = list(now_struct)
future_struct_list(3) += 1 # Add 1 to the hour (tm_hour)
future_struct = time.struct_time(future_struct_list)
# Convert back to a timestamp
future_timestamp = time.mktime(future_struct)
print(f"Current timestamp: {time.time():.0f}")
print(f"Timestamp in one hour: {future_timestamp:.0f}")
Output:
Current timestamp: 1754045415
Timestamp in one hour: 1754049015
. 10. Get the CPU time related to the thread time.thread_time()
In multi -threaded applications, time.process_time()
Provides you total CPU time for the whole process. But what if you would like to profile the use of a particular thread CPU? In this case, time.thread_time()
That is the function you are looking for. This function returns for the system and the user’s CPU time Current threadAllows you to identify which threads are the most expensive.
import time
import threading
def worker_task():
start_thread_time = time.thread_time()
# Simulate work
_ = (i * i for i in range(10_000_000))
end_thread_time = time.thread_time()
print(f"Worker thread CPU time: {end_thread_time - start_thread_time:.2f}s")
# Run the task in a separate thread
thread = threading.Thread(target=worker_task)
thread.start()
thread.join()
print(f"Total process CPU time: {time.process_time():.2f}s")
Output:
Worker thread CPU time: 0.23s
Total process CPU time: 0.32s
. Wrap
time
The module is an essential and powerful segment of the standard library. While time.sleep()
Of course it is its most famous function, time, period measurement, and time -to -form LIs make its capabilities a simple tool for all kinds of practical use tasks.
Going beyond the basics, you can learn new tricks to write more accurate and efficient code. For more advanced, object -based date and time manipulation, make sure to test amazing things you can do with datetime
The module next.
Matthew Mayo For,,,,,,,,,, for,, for,,,, for,,,, for,,, for,,,, for,,,, for,,,, for,,, for,,, for,,, for,,, for,,,, for,,, for,,, for,,,, for,,, for,,,, for,,, for,,, for,,,, for,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,,, for,,,, for,,,, for,,,, for,,,, for,,,, for,,, for,,, for,,, for,,, for,,,,, for,,,, for,,,, for,,,, for,, for,.@MattMayo13) Computer science is a graduate diploma in master’s degree and data mining. As the Managing Editor of Kdnuggets & StatologyAnd supporters in the editor Machine specializes in learningMatthew aims to make complex data science concepts accessible. Its professional interests include natural language processing, language models, machine learning algorithms, and the search for emerging AI. He is driven by a mission to democratic knowledge in the data science community. Matthew has been coding since the age of 6.