find the last accessed date of a file in python

To find the last accessed date of a file in Python, you can use the os.stat() function to get the file attributes, and then extract the st_atime attribute, which represents the time the file was last accessed, as a Unix timestamp. You can convert this timestamp to a human-readable format using the time.ctime() function.

Here's an example code snippet:

main.py
import os
import stat
import time

filename = 'path/to/your/file.txt'

# get the file attributes
file_stats = os.stat(filename)

# extract the last accessed time as a Unix timestamp
last_accessed_time = file_stats[stat.ST_ATIME]

# convert the timestamp to a human-readable format
last_accessed_time_str = time.ctime(last_accessed_time)

print(f"The file was last accessed on {last_accessed_time_str}")
403 chars
17 lines

Note that os.stat() returns a named tuple, where the element at index stat.ST_ATIME corresponds to the last accessed time.

related categories

gistlibby LogSnag