Python os.path.getatime() Method
The Python os.path.getatime() method is used to retrieve the last access time of a file or directory.
The method returns a floating-point number representing the time of the most recent access to 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.getatime() method −
os.path.getatime(path)
Parameter
This method accepts a string as a parameter representing the path to the file whose last access 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 last accessed.
Example
In the following example, we are retrieving the time of last access 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"
atime = os.path.getatime(file_path)
print("The file was accessed at:",atime)
Output
The output obtained is as follows −
The file was accessed at: 1640227200.0
Example
Here, we are retrieving the time of last access of the current directory and print it in seconds since the epoch −
import os
current_dir = os.getcwd()
atime = os.path.getatime(current_dir)
print("The directory was accessed at:",atime)
Output
Following is the output of the above code −
The directory was accessed at: 1714131137.8021567
Example
This example retrieves the time of last access of the file located on a Windows system using the getatime() method in human-readable format −
import os import time file_path = "C:\\Users\\Lenovo\\Downloads\\sql.txt" atime = os.path.getatime(file_path) print(time.ctime(atime))
Output
We get the output as shown below −
Fri Apr 26 18:30:51 2024
Example
If we attempt to retrieve the time of last access of a non-existent file path, the getatime() method raises the "FileNotFoundError" −
import os
link_path = "/non/existent/path"
atime = os.path.getatime(link_path)
print("The path was accessed at:",atime)
Output
The result produced is as shown below −
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
atime = os.path.getatime(link_path)
File "<frozen genericpath>", line 72, in getatime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'