Python os.path.getctime() Method
The Python os.path.getctime() method is used to get the creation time of a file or directory. The creation time represents the time when the file or directory's metadata was last changed. This includes changes to the file's permissions, ownership, or other metadata in addition to the creation time.
The method returns a floating-point number representing the creation time of the specified path, measured in seconds since the epoch (January 1, 1970, 00:00:00 UTC).
If the specified path does not exist or if there are permission issues preventing access to the path, the method raises a FileNotFoundError or PermissionError, respectively.
Syntax
Following is the basic syntax of the Python os.path.getctime() method −
os.path.getctime(path)
Parameter
This method accepts a string as a parameter representing the path to the file whose creation time you want to retrieve.
Return Value
The method returns a floating-point number representing the number of seconds since the epoch (January 1, 1970) when the file was created.
Example
In the following example, we are retrieving the time of creation of the file located at the given path "file_Path" and print it in seconds since the epoch −
import os
file_path = "/home/lenovo/documents/file.txt"
ctime = os.path.getctime(file_path)
print("The file was created at:",ctime)
Output
The output obtained is as follows −
The file was created at: 1640227200.0
Example
Here, we are retrieving the time of creation of the current directory and print it in seconds since the epoch −
import os
current_dir = os.getcwd()
ctime = os.path.getctime(current_dir)
print("The directory was created at:",ctime)
Output
Following is the output of the above code −
The directory was created at: 1656958586.0913115
Example
This example retrieves the time of creation of the file located on a Windows system using the getctime() method in human-readable format −
import os import time file_path = "C:\\Users\\Lenovo\\Downloads\\sql.txt" ctime = os.path.getctime(file_path) print(time.ctime(ctime))
Output
We get the output as shown below −
Thu Sep 14 17:25:33 2023
Example
If we attempt to retrieve the time of creation of a non-existent file path, the getctime() method raises the "FileNotFoundError" −
import os
link_path = "/non/existent/path"
ctime = os.path.getctime(link_path)
print("The path was modified at:",ctime)
Output
The result produced is as shown below −
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
ctime = os.path.getctime(link_path)
File "<frozen genericpath>", line 77, in getctime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'