How to set file modification time (mtime) in Python

Also see: How to set file access time (atime) 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 (mtime) use this snippet:

# mtime must be a datetime
stat = os.stat(filename)
# times must have two floats (unix timestamps): (atime, mtime)
os.utime(filename, times=(stat.st_atime, mtime.timestamp()))

Or use this utility function:

from datetime import datetime
import os

def set_file_modification_time(filename, mtime):
    """
    Set the modification time of a given filename to the given mtime.
    mtime must be a datetime object.
    """
    stat = os.stat(filename)
    atime = stat.st_atime
    os.utime(filename, times=(atime, mtime.timestamp()))

Usage example:

# Set the modification time of myfile.txt to 1980-1-1, leave the acess time intact
set_file_modification_time("myfile.txt", datetime(1980, 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_modification_time(filename, mtime):
    """
    Set the modification time of a given filename to the given mtime.
    mtime must be a datetime object.
    """
    stat = os.stat(filename)
    atime = stat.st_atime
    os.utime(filename, (atime, datetime_to_timestamp(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.