Python time Module

The time module in Python provides functions to work with various time-related tasks such as measuring time intervals, getting the current time, and formatting time values.

Some of the commonly used functions in the time module are:

  1. time() - returns the current system time in seconds since the epoch (January 1, 1970).

  2. localtime() - converts the current system time in seconds since the epoch to a time struct object representing the local time.

  3. gmtime() - converts the current system time in seconds since the epoch to a time struct object representing the UTC time.

  4. asctime() - converts a time struct object to a string representation of the time in a format like "Tue Dec 31 23:59:59 2019".

  5. strftime() - formats a time struct object into a string representation of the time according to a specified format.

Here is an example of how to use some of these functions:

import time

# Get the current system time
current_time = time.time()

# Convert the current system time to a time struct object representing the local time
local_time = time.localtime(current_time)

# Convert the current system time to a time struct object representing the UTC time
utc_time = time.gmtime(current_time)

# Convert the time struct object representing the local time to a string representation
local_time_string = time.asctime(local_time)

# Format the time struct object representing the local time into a custom string format
custom_time_format = "%Y-%m-%d %H:%M:%S"
custom_time_string = time.strftime(custom_time_format, local_time)

print("Current system time: ", current_time)
print("Local time: ", local_time)
print("UTC time: ", utc_time)
print("Local time string: ", local_time_string)
print("Custom time string: ", custom_time_string)
Sourc‮.www:e‬theitroad.com

Output:

Current system time:  1645982344.5930858
Local time:  time.struct_time(tm_year=2022, tm_mon=2, tm_mday=28, tm_hour=19, tm_min=32, tm_sec=24, tm_wday=0, tm_yday=59, tm_isdst=0)
UTC time:  time.struct_time(tm_year=2022, tm_mon=3, tm_mday=1, tm_hour=2, tm_min=32, tm_sec=24, tm_wday=1, tm_yday=60, tm_isdst=0)
Local time string:  Sun Feb 28 19:32:24 2022
Custom time string:  2022-02-28 19:32:24

In this example, we first import the time module. We then use the time() function to get the current system time in seconds since the epoch. We use the localtime() function to convert the current system time to a time struct object representing the local time, and the gmtime() function to convert it to a time struct object representing the UTC time. We use the asctime() function to convert the time struct object representing the local time to a string representation. We use the strftime() function to format the time struct object representing the local time into a custom string format. Finally, we print the results.