ANI

Amazing things you can do with Python's time module

Amazing things you can do with Python's time module
Photo for Editor | Chatgt

Obvious Introduction

Human developers are familiar with time module, with its as simple tasks as time.sleep(). This makes a modile gone to work with temporary setting, a simple but important tool. However, time The module is more flexible, giving a combination of direct measuring activities, time transforms, and formatting that is usually ignored. Testing these skills can open the most efficient ways of managing time related to time in your data science and other codes.

I have found the fullness of the creation of previous “amazing 10 articles”, and I get it. “Yes, it is so wonderful that I can do the time and jobs of Detertime Module, thank you.” Valid criticism. However, the word is attached because it looks like, so deal with it 🙂

In any case, here are 10 amazing and practical things you can do with Pyython's time Module.

Obvious 1. Suitably elapsed the past average clock time with time.monotonic()

While you could go time.time() measure how long the work takes, it has a critical error: Based on system clockby hand or network time agreements. This can lead to a condition of false or negative. A more powerful solution time.monotonic(). This work restores the number of monotonic clock, which cannot go back and are not affected with the updates time updates. This really makes good choices of time to measure time.

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.")

Which is output:

The task took 2.01 seconds.

Obvious 2. Measure time to process the CPU with time.process_time()

Sometimes, you don't care about the past time (a clock's clock time). Instead, you may want to know how long CPU has spent your code. This is important to balance algorithm's efficiency, as it does not ignore the time spent on sleep or waiting for I / O. This page time.process_time() The work returns the program of program and CPU CPU time for the current process, providing a pure rate of 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.")

Which is output:

The CPU-intensive task took 0.44 CPU seconds.

Obvious 3. Find higher timestamps with higher accuracy with time.perf_counter()

During the most accurate time, especially in very short periods, time.perf_counter() It is an important tool. Returns the high number of counter to resolve money, which is the most accurate clock found in your system. This is a broad range of system, which includes the past time during sleep, which makes it necessary to qualify the basic conditions where all nanoseconds list.

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.")

Which is output:

The short operation took 0.000028 seconds.

Obvious 4. Tick timethamp to read the ropes time.ctime()

The result of time.time() Is the floating that has been for the remaining seconds since “POCH” (January 1, 1970, with Unix programs). While useful in numbering, it is not readable by man. This page time.ctime() The work takes this last time and transforms us into a regular format, which is easy to read, like 'Tu Jul 31 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}")

Which is output:

Timestamp: 1754044568.821037
Readable Time: Fri Aug  1 06:36:08 2025

Obvious 5. PARSE TIME FROM THE FREE time.strptime()

Suppose you have time for the data stored as a string and you need to turn it into a systematic process. time.strptime() (The time of the framework of the framework) your work. You provide a string and format code that specifies how the structured comtracts is organized. Returns a struct_time Item, a feature that contains things – as a year, the moon, the day, and more – can be released.

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}")

Which is 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

Obvious 6. Time Format Format with custom cords time.strftime()

The opposite is formatting. time.strftime() (String time format) takes a struct_time Item (such as repaired strptime or localtime) And down the cord according to your specified format cows. This gives you full control, 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}.")

Which is output:

Custom formatted time: 2025-08-01 06:41:33
Today is Friday

Obvious 7. Find basic time information time.timezone including time.tzname

While store module (and librarian libraries like car) better with complex expiration expiry, the time Module provides specific basic information. time.timezone It provides Local and DST removal (time savings day) time for the time of the west of UTC, while time.tzname It is TUPLE containing the names of the Um-DST and DST Timezones.

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}")

Which is output:

Timezone offset: 5.0 hours west of UTC
Timezone names: ('EST', 'EDT')

Obvious 8. Turn between UTC and local time time.gmtime() including time.localtime()

Working at different times of time can be fake. The common practice is to keep all the joint time data for a local time (UTC) and turn it into a local time. This page time Module helps this with time.gmtime() including time.localtime(). These activities took time for seconds and returns a struct_time thing – gmtime() have you back to UTC, while localtime() Returns the time for your prepared time.

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)}")

Which is output:

UTC Time: 2025-08-01 10:47:58
Local Time: 2025-08-01 06:47:58

Obvious 9. Make an Inverse for time.time() reference time.mktime()

time.localtime() It changes time period into struct_time Item, useful … but how do you go in a funny way? This page time.mktime() The work is doing this directly. It takes a struct_time Item (representative of the local time) and convert you to the license for floating points representing seconds from the EPOch. This is useful in future calculation or past time period or making the arithmetic date.

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}")

Which is output:

Current timestamp: 1754045415
Timestamp in one hour: 1754049015

Obvious 10. Find the CPU cable time with time.thread_time()

For applications with many strips, time.process_time() gives you full CPU time in the entire process. But what if you want to install the CPU usage of a particular line? In this case, time.thread_time() the job you are looking for. This work restores the application of the program and time of CPU for Current cableallowing you to identify what the most expensive lids.

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")

Which is output:

Worker thread CPU time: 0.23s
Total process CPU time: 0.32s

Obvious Rolling up

This page time Module is an important and powerful for the common Pytho library. There time.sleep() There is no doubt that its most famous work, its estimating skills, timing skills, and the format, and the format of formats make it a practical tool for all kinds of useful works.

Traveling across the foundations, you can learn new code writing tactics and efficient code. In a high-quality, ranking rank in the correct action, make sure you look for amazing things you can do with datetime next module.

Matthew Mayo (@ mattma13) Holds the Master graduation in computer science and diploma graduated from the data mines. As the administrative editor of Kdnuggets & State, as well as a machine that does chinle in the Mastery learner, Matthew aims to make complex concepts of data science accessible. His technological interests include chronology, language models, studys of the machine, and testing ai. It is conducted by the purpose of democracy in the data science. Matthew has been with codes since he was 6 years old.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button