In this lesson we want to learn How to Use Python Time Module ? time
module in Python provides functions to work with time related values and operations. some of the common tasks you can perform using the time
module include:
- Getting the current time: You can use the
time
function to get the current time in seconds since the epoch (the starting point of time in computing).
1 2 3 |
import time current_time = time.time() print(current_time) |
- Converting time to readable format: You can use the
gmtime
andstrftime
functions to convert a time value to human readable format.
1 2 3 4 5 |
import time current_time = time.time() readable_time = time.gmtime(current_time) formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", readable_time) print(formatted_time) |
- Sleeping for a specific amount of time: You can use the
sleep
function to pause the execution of your program for a specified amount of time.
1 2 3 4 |
import time print("Start") time.sleep(5) print("End") |
- Measuring the elapsed time: You can use the
time
function to measure the elapsed time between two points in your program.
1 2 3 4 5 6 |
import time start_time = time.time() # Perform some operation end_time = time.time() elapsed_time = end_time - start_time print(elapsed_time) |
These are some of the basic uses of the time
module in Python. You can find more information about the time
module in the official Python documentation.
Here are some additional details about the time
module with examples:
- Converting local time to UTC: The
mktime
function can be used to convert local time expressed asstruct_time
to time expressed as a timestamp, assuming the local time is in UTC.
1 2 3 4 5 6 |
import time # convert local time to timestamp local_time = time.localtime() timestamp = time.mktime(local_time) print(timestamp) |
- Formatting time: The
strftime
function can be used to format the time, and thestrptime
function can be used to parse string representation of the time and return astruct_time
object.
1 2 3 4 5 6 7 8 9 10 11 |
import time # format time readable_time = time.gmtime() formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", readable_time) print(formatted_time) # parse time string time_string = "2022-06-24 11:00:00" parsed_time = time.strptime(time_string, "%Y-%m-%d %H:%M:%S") print(parsed_time) |
- Retrieving system timezone: The
tzname
function returns a tuple containing the names of the local time zone and the daylight saving time zone.
1 2 3 4 |
import time timezone = time.tzname print(timezone) |