如何从 python 设置文件的最后修改时间?

我有一个使用 Ftplib通过 FTP 下载文件的 python 脚本。

我当前的下载代码看起来就像 ftp lib docs 中的示例:

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

现在我要求通过 FTP 下载的文件需要与 FTP 服务器上的文件本身具有相同的最后修改时间。假设我可以从 ftp.retrlines('list')中解析出时间,那么如何在下载的文件上设置修改后的时间?

我用的是基于 Unix 的操作系统,如果这有关系的话。

57866 次浏览

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...

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