How to get last file access time (atime) in Python
To get the last access time of myfile.txt
in Python, use
import os
from datetime import datetime
datetime.fromtimestamp(os.stat("myfile.txt").st_atime)
You can also use this utility function:
import os
from datetime import datetime
def last_file_access_time(filename):
"""
Get a datetime() representing the last access time of the given file.
The returned datetime object is in local time
"""
return datetime.fromtimestamp(os.stat(filename).st_atime)
Note that os.stat("myfile.txt").st_atime
returns a Unix timestamp like 1563738878.1278138
(seconds passed since 1970-1-1 00:00:00
). This timestamp and the resulting datetime
we convert it to is in local time.
Remember that if the user has disabled access times on their filesystem (e.g. to save writes on a SSD), you have no way of finding out the last access date.