os.path.getatime() method is used to get the last access time of a file or directory. It returns the time as the number of seconds since the Unix epoch.
Example: In the following example, we get the last access time of a file.
import os
t = os.path.getatime("sample.txt")
print(t)
Output
1750123456.245891
Explanation: os.path.getatime("sample.txt") returns the last access time of the file as a floating-point value.
Syntax
os.path.getatime(path)
- Parameters: path - Path of the file or directory whose last access time is required.
- Return Value: Returns a floating-point value representing the last access time in seconds since the epoch.
Examples
Example 1: The following example retrieves and displays the last access time of a file.
import os
t = os.path.getatime("data.txt")
print(t)
Output
1750123456.245891
Explanation: os.path.getatime("data.txt") returns the timestamp of the file's most recent access.
Example 2: The following example converts the access timestamp into a human-readable date and time.
import os
import time
t = os.path.getatime("data.txt")
print(time.ctime(t))
Output
Mon Jun 13 10:25:16 2026
Explanation: time.ctime(t) converts the timestamp returned by os.path.getatime() into a readable date and time string.
Example 3: The following example checks a file's access time and handles the error if the file does not exist.
import os
try:
t = os.path.getatime("test.txt")
print(t)
except OSError:
print("File not found")
Output
File not found
Explanation: If the specified file does not exist, os.path.getatime() raises an OSError, which is handled using the try-except block.