How to set file access time (atime) in Python
Also see: How to set file modification time (mtime) in Python
You can use os.utime()
to set the access and modification times of files in Python. In order to set just the access time (atime
) use this snippet:
# atime must be a datetime
stat = os.stat(filename)
# times must have two floats (unix timestamps): (atime, mtime)
os.utime(filename, times=(atime.timestamp(), stat.st_mtime))
Or use this utility function:
from datetime import datetime
import os
def set_file_access_time(filename, atime):
"""
Set the access time of a given filename to the given atime.
atime must be a datetime object.
"""
stat = os.stat(filename)
mtime = stat.st_mtime
os.utime(filename, times=(atime.timestamp(), mtime))
Usage example:
# Set the access time of myfile.txt to 1970-1-1, leave the modification time intact
set_file_access_time("myfile.txt", datetime(1970, 1, 1, 0, 0, 0))
In case you need to compatible with Python 2.x, use this variant instead:
from datetime import datetime
import os
import time
def datetime_to_timestamp(dt):
return time.mktime(dt.timetuple()) + dt.microsecond/1e6
def set_file_access_time(filename, atime):
"""
Set the access time of a given filename to the given atime.
atime must be a datetime object.
"""
stat = os.stat(filename)
mtime = stat.st_mtime
os.utime(filename, (datetime_to_timestamp(atime), mtime))
See How to convert datetime to time float (unix timestamp) in Python 2 and How to fix Python error AttributeError: datetime.datetime object has no attribute timestamp for more details on this alternate approach.
In case you have any option of using Python 3.x, I recommend using the Python 3 version listed above, since it’s much more readable, involves less code and (at the time of writing this code), Python 2 will be retired in only a couple of months. I recommend upgrading your scripts with Python 3 compatibility as soon as possible as many other projects have already done.