How can I set the last modified time of a file from python?

Use os.utime:

import os

os.utime(path_to_file, (access_time, modification_time))

More elaborate example: https://www.tutorialspoint.com/python/os_utime.htm


To edit a file last modified field, use:

os.utime(<file path>, (<access date epoch>, <modification date epoch>))

Example:

os.utime(r'C:\my\file\path.pdf', (1602179630, 1602179630))

💡 - Epoch is the number of seconds that have elapsed since January 1, 1970. see more


If you are looking for a datetime version:

import datetime
import os

def set_file_last_modified(file_path, dt):
    dt_epoch = dt.timestamp()
    os.utime(file_path, (dt_epoch, dt_epoch))

# ...

now = datetime.datetime.now()
set_file_last_modified(r'C:\my\file\path.pdf', now)

💡 - For Python versions < 3.3 use dt_epoch = time.mktime(dt.timetuple())