In Python, the time module is part of the standard library and is used for working with time-related tasks. It provides access to time-related functions that are crucial for applications involving delays, timestamps, performance measurement, and formatted time output. This document offers a comprehensive overview of the time module, its functions, and real-world usage examples.
Before using any functionality from the time module, it must be imported:
import time
Epoch is the point where the time starts. On most systems, the epoch is January 1, 1970, 00:00:00 (UTC). The time module works with time values as the number of seconds since the epoch.
This function returns the current time in seconds since the epoch as a floating-point number.
current_time = time.time()
print("Seconds since epoch:", current_time)
Used to delay the execution of the program for a given number of seconds.
print("Start sleeping...")
time.sleep(3)
print("Woke up after 3 seconds")
Many functions in the time module either accept or return time in struct_time format. It is a named tuple with nine components: year, month, day, hour, minute, second, weekday, yearday, and DST flag.
Returns the current local time as a struct_time object.
local = time.localtime()
print("Local time:", local)
print("Year:", local.tm_year)
print("Month:", local.tm_mon)
print("Day:", local.tm_mday)
Returns the current time in UTC as a struct_time object.
utc_time = time.gmtime()
print("UTC time:", utc_time)
Converts a struct_time to seconds since the epoch.
timestamp = time.mktime(local)
print("Epoch time:", timestamp)
Converts a struct_time object to a string representation, based on the format string provided.
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local)
print("Formatted:", formatted)
Parses a string into a struct_time object based on the specified format.
date_string = "2025-06-27 15:30:00"
parsed = time.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed struct_time:", parsed)
Converts a struct_time to a readable 24-character string.
readable = time.asctime(local)
print("Asctime:", readable)
Returns a human-readable string representation of the time.
print("Current time:", time.ctime())
Returns the value of a high-resolution performance counter, useful for benchmarking.
start = time.perf_counter()
time.sleep(1.5)
end = time.perf_counter()
print("Elapsed time:", end - start)
Returns the CPU time used by the current process.
start = time.process_time()
for i in range(1000000):
pass
end = time.process_time()
print("CPU time:", end - start)
Returns a monotonic clock, which means the value cannot go backward.
start = time.monotonic()
time.sleep(2)
end = time.monotonic()
print("Monotonic time:", end - start)
Returns the offset in seconds of the local non-DST timezone from UTC.
print("Timezone offset (seconds):", time.timezone)
Returns the offset during DST.
print("DST offset (seconds):", time.altzone)
Returns whether DST is in effect (1) or not (0).
print("Is daylight saving time used?", time.daylight)
Returns a tuple of two strings: standard time and DST time zone names.
print("Time zone names:", time.tzname)
import time
def countdown(seconds):
while seconds:
print("Time left:", seconds)
time.sleep(1)
seconds -= 1
print("Time's up!")
countdown(5)
def log_event(event):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"[{timestamp}] {event}")
log_event("Application Started")
time.sleep(2)
log_event("Application Ended")
def sample_function():
total = 0
for i in range(1000000):
total += i
return total
start = time.perf_counter()
sample_function()
end = time.perf_counter()
print("Function execution time:", end - start)
with open("log.txt", "a") as f:
f.write(f"{time.ctime()} - Task completed\n")
for i in range(3):
print("Running task", i + 1)
time.sleep(1)
import time
while True:
print(time.strftime("%H:%M:%S", time.localtime()))
time.sleep(1)
date_string = "2025-06-27 14:00:00"
struct = time.strptime(date_string, "%Y-%m-%d %H:%M:%S")
epoch = time.mktime(struct)
print("Epoch time:", epoch)
formatted = time.strftime("%A, %d %B %Y", time.localtime(epoch))
print("Formatted:", formatted)
Always be cautious when comparing two floating-point time values due to potential rounding errors.
Use time.perf_counter() for benchmarking over time.time().
Not all time module features behave the same on every platform. For example, time.clock() was deprecated and removed in Python 3.8.
The Python time module is a versatile and essential part of time-based programming. Whether you are building countdown timers, logging systems, performance benchmarks, or simply need to delay execution, understanding the capabilities of this module is critical. Its combination with other modules such as datetime or threading makes it even more powerful. Mastering its use prepares you to tackle a broad range of programming challenges effectively and efficiently.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved