46. Python's time Module

Here are 10 Python code snippets that demonstrate the use of the time module, covering various time-related functionalities such as sleeping, measuring elapsed time, formatting time, and more.


1. Sleeping for a Specified Time

Pausing the program execution for a specified number of seconds.

import time

print("Program starts")
time.sleep(3)  # Pauses for 3 seconds
print("Program resumes after 3 seconds")

This will make the program pause for 3 seconds before resuming execution.


2. Measuring Elapsed Time with time.time()

Using time.time() to measure the elapsed time between two points in the program.

import time

start_time = time.time()

# Some time-consuming task
time.sleep(2)

end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} seconds")

This example measures the time taken for a sleep period of 2 seconds.


3. Formatting Current Time with time.strftime()

Formatting the current time as a human-readable string.

This will print the current date and time in the format YYYY-MM-DD HH:MM:SS.


4. Converting Time to Seconds with time.mktime()

Converting a struct_time to seconds since the epoch.

This converts the current time to the number of seconds since the Unix epoch.


5. Getting the Current Time in Epoch Format

Getting the current time in seconds since the Unix epoch.

This prints the current time in seconds since January 1, 1970.


6. Pausing Program for User Input Delay

Pausing the program until the user presses a key.

This introduces a delay before accepting user input.


7. Time-based Loop (Periodic Tasks)

Running a periodic task every 2 seconds.

This example runs a task every 2 seconds.


8. Get the Time in Different Time Zones

Using time and pytz module (if installed) to get the time in different time zones.

This shows how you could use time with pytz for time zone handling.


9. Calculating Execution Time Using time.perf_counter()

Using time.perf_counter() for precise time measurements.

time.perf_counter() provides a high-resolution timer to measure short durations accurately.


10. Getting the Current Time in UTC

Getting the current time in UTC format.

This will print the current time in UTC, formatted as YYYY-MM-DD HH:MM:SS.


These examples showcase how you can work with time-related functionality in Python, including sleeping, measuring time intervals, formatting time, and working with different time zones.

Last updated