You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中无需子命令修改文件的创建和修改时间?

如何用Python修改文件的访问时间和修改时间(无需直接调用os/subprocess)

你之前用Pathlib('./file.jpg').touch()和os.utime('./file.jpg', None)无效,是因为这两个调用默认都会使用当前系统时间,而非你指定的目标时间。要实现类似touch -a -m -t的效果,只需给方法传入指定时间参数即可,以下是具体实现:

方法1:Python 3.10+ 推荐(Pathlib原生支持)

Python 3.10及以上版本的Path.touch()支持直接传入atime(访问时间)和mtime(修改时间)参数,先把目标时间转换成带时区的datetime对象即可:

from pathlib import Path
from datetime import datetime, timezone, timedelta

# 对应示例中的目标时间:2015-12-18 01:30:09-05:00
target_datetime = datetime(
    year=2015, month=12, day=18,
    hour=1, minute=30, second=9,
    tzinfo=timezone(-timedelta(hours=5))
)

file = Path("./file.jpg")
# exist_ok=True确保文件已存在时不报错,同时覆盖指定的访问/修改时间
file.touch(exist_ok=True, atime=target_datetime, mtime=target_datetime)

方法2:兼容Python 3.9及以下版本

如果你的Python版本低于3.10,Path.touch()不支持atime和mtime参数,可通过Path对象配合时间戳实现(注:底层仍依赖os模块,但属于标准库封装调用):

from pathlib import Path
from datetime import datetime, timezone, timedelta
import os

# 转换目标时间为时间戳(秒级)
target_datetime = datetime(2015, 12, 18, 1, 30, 9, tzinfo=timezone(-timedelta(hours=5)))
timestamp = target_datetime.timestamp()

file = Path("./file.jpg")
# 同时设置访问时间和修改时间
os.utime(file.resolve(), (timestamp, timestamp))

验证修改结果

用你之前的命令即可确认时间修改成功:

# 查看文件修改时间
ls -l --time-style=full-iso ./file.jpg

# 查看文件详细时间属性
exiftool ./file.jpg | grep -i date

注意事项

  • 必须传入带时区的datetime对象,否则Python会默认使用本地时区,可能导致时间与预期偏差。
  • 如果目标文件不存在,touch会自动创建它;加上exist_ok=True可避免文件已存在时抛出异常。

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:50:34