本文目录导读:

这里提供几个批量修改文件日期的脚本方案,涵盖不同操作系统和需求场景:
Linux/Mac (使用 touch 命令)
修改为当前时间
# 修改当前目录所有文件的访问和修改时间为当前时间
for file in *; do
touch "$file"
done
# 或使用 find 递归修改
find . -type f -exec touch {} \;
修改为指定时间
# 修改为 2025-01-15 10:30:00
for file in *; do
touch -t 202501151030 "$file"
done
# touch 时间格式:[[CC]YY]MMDDhhmm[.ss]
# 202501151030.00
只修改修改时间(mtime)
# 修改 mtime 为当前时间
find . -type f -exec touch -m {} \;
# 或修改为指定时间
for file in *; do
touch -m -t 202501151030 "$file"
done
Windows PowerShell
修改为当前时间
# 修改当前目录所有文件
Get-ChildItem -File | ForEach-Object {
$_.LastWriteTime = Get-Date
$_.CreationTime = Get-Date
$_.LastAccessTime = Get-Date
}
# 递归修改子目录
Get-ChildItem -File -Recurse | ForEach-Object {
$_.LastWriteTime = Get-Date
}
修改为指定时间
# 修改为 2025年1月15日 10:30:00
$targetTime = Get-Date "2025-01-15 10:30:00"
Get-ChildItem -File | ForEach-Object {
$_.LastWriteTime = $targetTime
$_.CreationTime = $targetTime
$_.LastAccessTime = $targetTime
}
只修改特定类型文件
# 只修改 .txt 文件
Get-ChildItem -Filter "*.txt" -File | ForEach-Object {
$_.LastWriteTime = Get-Date
}
Python 跨平台脚本
基础版本
import os
import time
from datetime import datetime
def modify_file_dates(directory, target_date=None, recursive=False):
"""
批量修改文件日期
Args:
directory: 目标目录
target_date: 目标日期,格式 "YYYY-MM-DD HH:MM:SS",None 表示当前时间
recursive: 是否递归子目录
"""
# 设定目标时间
if target_date:
target_time = datetime.strptime(target_date, "%Y-%m-%d %H:%M:%S").timestamp()
else:
target_time = time.time()
# 遍历文件
for root, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
try:
# 修改访问和修改时间
os.utime(filepath, (target_time, target_time))
print(f"✓ 修改: {filepath}")
except Exception as e:
print(f"✗ 失败: {filepath} - {e}")
if not recursive:
break
# 使用示例
if __name__ == "__main__":
# 修改当前目录所有文件为当前时间
modify_file_dates(".")
# 修改为指定时间并递归子目录
# modify_file_dates(".", "2025-01-15 10:30:00", recursive=True)
高级版本(带筛选和备份)
import os
import time
import shutil
from datetime import datetime
class FileDateModifier:
def __init__(self):
self.modified_count = 0
self.failed_files = []
def backup_file(self, filepath):
"""创建备份文件"""
backup_path = filepath + ".bak"
shutil.copy2(filepath, backup_path)
return backup_path
def modify_dates(self, directory, target_date=None,
recursive=False, file_pattern=None,
backup=False, modify_types=['mtime', 'atime']):
"""
高级文件日期修改
Args:
directory: 目标目录
target_date: 目标日期字符串,格式 "YYYY-MM-DD HH:MM:SS"
recursive: 是否递归
file_pattern: 文件匹配模式(可选),如 .txt, .jpg
backup: 是否备份原文件
modify_types: 修改的时间类型,['atime'], ['mtime'], 或 ['atime', 'mtime']
"""
# 解析目标时间
if target_date:
target_time = datetime.strptime(target_date, "%Y-%m-%d %H:%M:%S").timestamp()
else:
target_time = time.time()
# 获取文件列表
file_list = []
for root, dirs, files in os.walk(directory):
for filename in files:
if file_pattern and not filename.endswith(file_pattern):
continue
filepath = os.path.join(root, filename)
file_list.append(filepath)
if not recursive:
break
print(f"找到 {len(file_list)} 个要处理的文件")
print(f"目标时间: {datetime.fromtimestamp(target_time)}")
print(f"修改属性: {', '.join(modify_types)}")
print("-" * 50)
# 处理每个文件
for filepath in file_list:
try:
# 可选:备份
if backup:
backup_path = self.backup_file(filepath)
print(f"✓ 已备份: {backup_path}")
# 获取当前时间戳
stats = os.stat(filepath)
atime = stats.st_atime # 访问时间
mtime = stats.st_mtime # 修改时间
# 修改指定时间
new_atime = target_time if 'atime' in modify_types else atime
new_mtime = target_time if 'mtime' in modify_types else mtime
os.utime(filepath, (new_atime, new_mtime))
self.modified_count += 1
print(f"✓ {self.modified_count}. 修改: {os.path.basename(filepath)}")
except Exception as e:
self.failed_files.append((filepath, str(e)))
print(f"✗ 失败: {filepath}")
print(f" 错误: {e}")
# 打印统计信息
print("-" * 50)
print(f"完成!成功修改: {self.modified_count} 个文件")
if self.failed_files:
print(f"失败: {len(self.failed_files)} 个文件")
for f, e in self.failed_files:
print(f" - {f}: {e}")
# 使用示例
if __name__ == "__main__":
modifier = FileDateModifier()
# 修改当前目录所有 .txt 文件为当前时间(不递归)
modifier.modify_dates(
directory=".",
recursive=False,
file_pattern=".txt"
)
# 递归修改所有文件为指定时间并备份
# modifier.modify_dates(
# directory="./documents",
# target_date="2025-01-15 10:30:00",
# recursive=True,
# backup=True,
# modify_types=['mtime'] # 只修改修改时间
# )
批处理文件(Windows)
保存为 modify_date.bat:
@echo off
chcp 65001 >nul
echo 批量修改文件日期工具
echo ============================
:: 设置目标日期 (格式: YYYY-MM-DD)
set TARGET_DATE=2025-01-15
:: 设置目标时间 (格式: HH:MM:SS)
set TARGET_TIME=10:30:00
:: 修改当前目录所有文件
for %%f in (*) do (
if not "%%f"=="%~nx0" (
echo 修改: %%f
copy /b "%%f"+,, >nul
)
)
echo 完成!
pause
使用建议
- 先测试小范围:在实际应用前,先用小文件夹测试
- 备份重要文件:修改文件时间可能影响一些依赖时间戳的应用
- 权限问题:某些文件可能需要管理员权限才能修改
- 文件系统限制:FAT32 等旧文件系统可能有不支持的特性
选择最适合你需求的方案即可,如果不需要备份功能,方案一的 Linux/Mac 命令或 Windows PowerShell 最简洁;如果需要更复杂的控制,推荐使用 Python 脚本。