怎么改变文件的修改日期和时间(图文)
改变文件的修改日期和时间有多种方法,以下是针对不同操作系统的详细说明:
使用
使用
1. Linux/macOS 系统
使用 touch 命令
基本语法
bash
touch -m -t [[CC]YY]MMDDhhmm[.ss] filename具体示例
bash
# 修改单个文件的修改时间为 2023年12月25日14:30:00 touch -m -t 202312251430.00 filename.txt # 修改为当前时间 touch -m filename.txt # 修改多个文件 touch -m -t 202312251430 *.txt # 递归修改目录下所有文件 find /path/to/directory -type f -exec touch -m -t 202312251430 {} \;使用 stat 命令查看修改时间
bash
# 查看文件详细信息 stat filename.txt # 只查看修改时间 stat -c %y filename.txt2. Windows 系统
使用 PowerShell
powershell
# 修改单个文件的最后写入时间 (Get-Item "filename.txt").LastWriteTime = "2023-12-25 14:30:00" # 修改创建时间 (Get-Item "filename.txt").CreationTime = "2023-12-25 14:30:00" # 修改访问时间 (Get-Item "filename.txt").LastAccessTime = "2023-12-25 14:30:00" # 批量修改多个文件 Get-ChildItem "*.txt" | ForEach-Object { $_.LastWriteTime = "2023-12-25 14:30:00" }使用命令提示符
cmd
# 复制文件自身来更新时间戳 copy /b filename.txt +,, # 批量更新 for %f in (*.txt) do copy /b "%f" +,,3. 编程方式修改
Python 脚本
python
import os import time from datetime import datetime def change_file_mtime(filepath, date_string): """ 修改文件的修改时间 :param filepath: 文件路径 :param date_string: 日期字符串,格式如 "2023-12-25 14:30:00" """ # 转换日期字符串为时间戳 dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") timestamp = time.mktime(dt.timetuple()) # 获取当前访问时间 current_atime = os.path.getatime(filepath) # 设置新的修改时间(保持访问时间不变) os.utime(filepath, (current_atime, timestamp)) print(f"已将 {filepath} 的修改时间改为 {date_string}") # 使用示例 change_file_mtime("filename.txt", "2023-12-25 14:30:00") # 批量修改 import glob for file in glob.glob("*.txt"): change_file_mtime(file, "2023-12-25 14:30:00")Node.js 脚本
javascript
const fs = require('fs'); function changeFileMtime(filepath, dateString) { // 转换日期字符串为时间戳 const timestamp = new Date(dateString).getTime() / 1000; // 获取当前访问时间 const stats = fs.statSync(filepath); const atime = stats.atime.getTime() / 1000; // 设置新的修改时间 fs.utimesSync(filepath, atime, timestamp); console.log(`已将 ${filepath} 的修改时间改为 ${dateString}`); } // 使用示例 changeFileMtime('filename.txt', '2023-12-25 14:30:00');4. 高级批量操作
按条件筛选文件修改
bash
# 只修改特定大小的文件 find . -type f -size +1M -exec touch -m -t 202312251430 {} \; # 只修改最近7天内修改过的文件 find . -type f -mtime -7 -exec touch -m -t 202312251430 {} \; # 按文件类型筛选 find . \( -name "*.jpg" -o -name "*.png" \) -exec touch -m -t 202312251430 {} \;保持相对时间关系
bash
#!/bin/bash # 脚本保持文件间的相对时间顺序 REFERENCE_FILE="reference.txt" TARGET_TIME="202312251430" # 获取参考文件的时间差 TIME_DIFF=$(($(date +%s) - $(stat -c %Y "$REFERENCE_FILE"))) # 为所有文件设置基于参考时间的新时间 find . -type f -exec sh -c ' for file; do original_time=$(stat -c %Y "$file") new_time=$((original_time + TIME_DIFF)) touch -m -d "@$new_time" "$file" done ' _ {} +5. 图形界面工具
Linux GUI 工具
- Nautilus (文件管理器): 右键属性 → 信息标签页
- Thunar: 右键 → 属性 → 常规标签页
Windows GUI 工具
- 资源管理器: 右键文件 → 属性 → 常规标签页
- 第三方工具如 BulkFileChanger
6. 注意事项
- 权限要求: 需要对文件有写权限才能修改时间戳
- 时间格式: 不同系统对时间格式的要求可能不同
- 审计影响: 修改系统文件时间戳可能影响系统审计
- 备份建议: 批量操作前建议备份重要文件

更新时间:2025-12-15 13:19:03
下一篇:如何修改文件修改日期(图文)
