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

3

107

I have a python script that downloads a file over FTP using ftplib.

My current download code looks just like the example in the ftp lib docs:

ftp.retrbinary('RETR README', open('README', 'wb').write)

Now I have a requirement that the file downloaded over FTP needs to have the same last modified time as the file on the FTP server itself. Assuming I could parse out the time from ftp.retrlines('list'), how can I set the modified time on the downloaded file?

I'm on a unix based OS if that matters.

Nesmith answered 5/7, 2012 at 16:50 Comment(0)
C
114

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

Christianachristiane answered 3/8, 2016 at 21:40 Comment(4)
this answer could be improved with an example and discussion of the format of that time; specifically an epoch; IE @jossef's answer.Gio
This doesn't work for dates before 1980 on Windows, correct? (Why do I wanted to set date modified before 1980, you ask? Because that's what Google Photos uses when I drag files in).Frumentaceous
Actually I think the value IS being set for dates before 1980. It's just blank when viewed in Windows File Explorer.Frumentaceous
In case someone only wants to update the "last modifed" date to the current time, simply calling os.utime(path_to_file) does the job.Brame
L
51

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())

Legionary answered 8/10, 2020 at 18:0 Comment(2)
Thank you for this answer; it contains examples, is detailed and helpful.Gio
This should have been the answer. but it is 8 years lateGrumous
D
21

There are 2 ways to do this. One is the os.utime example which is required if you are setting the timestamp on a file that has no reference stats.

However, if you are copying the files with shutil.copy() you have a reference file. Then if you want the permission bits, last access time, last modification time, and flags also copied, you can use shutil.copystat() immediately after the shutil.copy().

And then there is shutil.copy2 which is intended to do both at once...

Director answered 12/9, 2014 at 18:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.