如何在 Python 中设置文件修改时间(mtime)
另请参见:如何在 Python 中设置文件访问时间(atime)
你可以使用 os.utime() 在 Python 中设置文件的访问和修改时间。为了仅设置访问时间(mtime),使用此代码片段:
set_mtime.py
# mtime 必须是 datetime
stat = os.stat(filename)
# times 必须有两个浮点数(unix 时间戳):(atime, mtime)
os.utime(filename, times=(stat.st_atime, mtime.timestamp()))或使用此实用函数:
set_mtime_util.py
from datetime import datetime
import os
def set_file_modification_time(filename, mtime):
"""
将给定文件名的修改时间设置为给定的 mtime。
mtime 必须是 datetime 对象。
"""
stat = os.stat(filename)
atime = stat.st_atime
os.utime(filename, times=(atime, mtime.timestamp()))用法示例:
set_mtime_usage.py
# 将 myfile.txt 的修改时间设置为 1980-1-1,保持访问时间不变
set_file_modification_time("myfile.txt", datetime(1980, 1, 1, 0, 0, 0))如果你需要兼容 Python 2.x,请使用此变体:
set_mtime_py2_compat.py
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):
"""
将给定文件名的修改时间设置为给定的 mtime。
mtime 必须是 datetime 对象。
"""
stat = os.stat(filename)
atime = stat.st_atime
os.utime(filename, (atime, datetime_to_timestamp(mtime)))请参见如何在 Python 2 中将 datetime 转换为 time float(unix 时间戳)和如何修复 Python 错误 AttributeError: datetime.datetime object has no attribute timestamp了解此替代方法的更多详细信息。
如果你有任何使用 Python 3.x 的选择,我建议使用上面列出的 Python 3 版本,因为它更易读、涉及更少的代码,并且(在编写此代码时),Python 2 将在几个月内退役。我建议尽快升级你的脚本以兼容 Python 3,正如许多其他项目已经做的那样。
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow