Python 3 – time ctime() Method
Python Time module provides a way to handle various operations related to time. The ctime()
method is one of the most commonly used methods in the time module. This method returns a string representing the current local time.
import time
# current time
current_time = time.ctime()
print("Current Time is: ", current_time)
The output of the above code will be as follows:
Current Time is: Mon Aug 24 16:18:07 2020
Syntax
The syntax of the ctime()
method is very simple.
time.ctime(seconds)
Here, seconds
is an optional argument. If the argument is not provided, the method returns the current time. Otherwise, it returns the local time corresponding to the seconds since the epoch.
import time
# convert seconds to local time
local_time = time.ctime(1598262283.7267323)
print("Local Time is: ", local_time)
The output of the above code will be as follows:
Local Time is: Mon Aug 24 16:18:03 2020
Example: Using ctime() to get File Modification Time
The ctime()
method can be used along with other modules like os to get the details of a file. In the below code sample, we use the os.path.getctime(path)
method to get the creation time of a file, which is supplied as the path
argument to the method. Once we have the creation time in seconds, we use the ctime()
method to convert the seconds to local time.
import os
import time
# specify file path
path = "sample.txt"
# get the creation time of file
create_time = os.path.getctime(path)
# convert the creation time to local time
local_time = time.ctime(create_time)
print("File creation time is: ", local_time)
The output of the above code sample will be as follows:
File creation time is: Mon Aug 24 16:18:05 2020
Conclusion
Hence, we have learned how to use the ctime()
method of the Python time module to get the current local time or to convert seconds to local time. We have also learned how to use this method to get the file creation time using the os module. This method is very helpful in many scenarios where the local time needs to be displayed or timestamp needs to be converted to a human-readable format.