Get File Last Access Time in Python


Python - Get File Last Access Time

To get last access time of a file in Python, you can use the os.path module. Call os.path.getatime() function and pass the file path as argument to the function.

The function returns a number giving the number of seconds since the epoch. You may use datetime library to format it to a specific datetime format.

The syntax to call os.path.getatime() function to get the time when the file was last accessed is

import os

os.path.getatime(file_path)

Example

In the following program, we get the last accessed time of the file data.txt programmatically using os.path.getatime() function.

Python Program

import os
import datetime

file_path = 'myfolder/data.txt'

#get last accessed time
n = os.path.getatime(file_path)

#convert epoch to a timestamp
timestamp = datetime.datetime.fromtimestamp(n).strftime('%c')
print(timestamp)

Output

Mon Jan 16 22:17:38 2023

Summary

In this tutorial of Python Examples, we learned how to get the last accessed time of a file using os.path.getatime() function, with the help of examples.