相较于1.0,增加了随机时间范围偏移的功能
import os
import sys
import random
from datetime import datetime, timedelta
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,QWidget, QLabel, QComboBox, QDateTimeEdit, QPushButton,QFileDialog, QCheckBox, QScrollArea, QGroupBox, QSpinBox,QMessageBox)
from PyQt5.QtCore import QDateTime, Qtclass FileTimeModifier(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle("文件修改时间批量修改工具 (带随机偏移)")self.setGeometry(100, 100, 900, 600)# 主部件和布局self.main_widget = QWidget()self.main_layout = QVBoxLayout()# 顶部控制区域self.control_group = QGroupBox("控制面板")self.control_layout = QVBoxLayout()# 第一行按钮self.button_row1 = QHBoxLayout()self.add_button = QPushButton("添加文件")self.add_button.clicked.connect(self.add_files)self.select_all_checkbox = QCheckBox("全选")self.select_all_checkbox.stateChanged.connect(self.toggle_select_all)self.modify_button = QPushButton("应用修改")self.modify_button.clicked.connect(self.modify_files)self.button_row1.addWidget(self.add_button)self.button_row1.addWidget(self.select_all_checkbox)self.button_row1.addWidget(self.modify_button)# 第二行随机偏移设置self.random_row = QHBoxLayout()self.random_label = QLabel("随机偏移范围:")self.random_days = QSpinBox()self.random_days.setRange(0, 365)self.random_days.setValue(0)self.random_days.setSuffix(" 天")self.random_hours = QSpinBox()self.random_hours.setRange(0, 23)self.random_hours.setValue(0)self.random_hours.setSuffix(" 小时")self.random_minutes = QSpinBox()self.random_minutes.setRange(0, 59)self.random_minutes.setValue(0)self.random_minutes.setSuffix(" 分钟")self.random_seconds = QSpinBox()self.random_seconds.setRange(0, 59)self.random_seconds.setValue(0)self.random_seconds.setSuffix(" 秒")self.random_row.addWidget(self.random_label)self.random_row.addWidget(self.random_days)self.random_row.addWidget(self.random_hours)self.random_row.addWidget(self.random_minutes)self.random_row.addWidget(self.random_seconds)self.random_row.addStretch()# 添加到控制面板self.control_layout.addLayout(self.button_row1)self.control_layout.addLayout(self.random_row)self.control_group.setLayout(self.control_layout)# 滚动区域用于文件列表self.scroll_area = QScrollArea()self.scroll_widget = QWidget()self.scroll_layout = QVBoxLayout()# 初始文件列表self.file_entries = []self.scroll_widget.setLayout(self.scroll_layout)self.scroll_area.setWidget(self.scroll_widget)self.scroll_area.setWidgetResizable(True)# 添加到主布局self.main_layout.addWidget(self.control_group)self.main_layout.addWidget(self.scroll_area)self.main_widget.setLayout(self.main_layout)self.setCentralWidget(self.main_widget)# 获取当前目录下的文件self.refresh_file_list()def refresh_file_list(self):"""刷新当前目录下的文件列表"""# 清空现有条目for entry in self.file_entries:entry['widget'].setParent(None)self.file_entries.clear()# 获取当前目录下的所有文件current_dir = os.path.dirname(os.path.abspath(__file__))files = [f for f in os.listdir(current_dir) if os.path.isfile(os.path.join(current_dir, f))]# 为每个文件创建条目for file in files:self.add_file_entry(file)def add_file_entry(self, filename):"""为单个文件创建UI条目"""entry_widget = QWidget()entry_layout = QHBoxLayout()# 复选框checkbox = QCheckBox()checkbox.setChecked(True)# 文件名标签file_label = QLabel(filename)file_label.setMinimumWidth(200)# 修改时间选择器time_edit = QDateTimeEdit()time_edit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")time_edit.setDateTime(QDateTime.currentDateTime())# 随机偏移后的时间标签random_time_label = QLabel("")random_time_label.setMinimumWidth(150)# 添加到布局entry_layout.addWidget(checkbox)entry_layout.addWidget(file_label)entry_layout.addWidget(time_edit)entry_layout.addWidget(QLabel("→"))entry_layout.addWidget(random_time_label)entry_widget.setLayout(entry_layout)# 保存条目信息self.file_entries.append({'widget': entry_widget,'checkbox': checkbox,'filename': filename,'time_edit': time_edit,'random_time_label': random_time_label})# 添加到滚动区域self.scroll_layout.addWidget(entry_widget)# 连接信号,当时间改变时更新随机时间显示time_edit.dateTimeChanged.connect(self.update_random_time_display)def update_random_time_display(self):"""更新所有条目的随机时间显示"""for entry in self.file_entries:base_time = entry['time_edit'].dateTime().toPyDateTime()random_offset = self.calculate_random_offset()random_time = base_time + random_offsetentry['random_time_label'].setText(random_time.strftime("%Y-%m-%d %H:%M:%S"))def calculate_random_offset(self):"""计算随机时间偏移量"""days = self.random_days.value()hours = self.random_hours.value()minutes = self.random_minutes.value()seconds = self.random_seconds.value()# 计算总秒数范围total_seconds_range = (days * 86400 + hours * 3600 +minutes * 60 + seconds)if total_seconds_range == 0:return timedelta(0)# 随机正负偏移random_seconds = random.randint(-total_seconds_range, total_seconds_range)return timedelta(seconds=random_seconds)def add_files(self):"""添加文件到列表"""current_dir = os.path.dirname(os.path.abspath(__file__))files, _ = QFileDialog.getOpenFileNames(self, "选择文件", current_dir)for file in files:filename = os.path.basename(file)# 检查是否已存在if not any(entry['filename'] == filename for entry in self.file_entries):self.add_file_entry(filename)def toggle_select_all(self, state):"""全选/取消全选"""for entry in self.file_entries:entry['checkbox'].setChecked(state == Qt.Checked)def modify_files(self):"""修改选中的文件的修改时间"""current_dir = os.path.dirname(os.path.abspath(__file__))modified_count = 0for entry in self.file_entries:if entry['checkbox'].isChecked():filepath = os.path.join(current_dir, entry['filename'])base_time = entry['time_edit'].dateTime().toPyDateTime()# 计算随机偏移random_offset = self.calculate_random_offset()new_time = base_time + random_offset# 转换为时间戳timestamp = new_time.timestamp()# 修改文件时间try:os.utime(filepath, (timestamp, timestamp))modified_count += 1except Exception as e:print(f"修改文件 {entry['filename']} 时间失败: {e}")# 显示修改结果QMessageBox.information(self, "操作完成",f"成功修改了 {modified_count} 个文件的修改时间")# 刷新随机时间显示self.update_random_time_display()if __name__ == "__main__":app = QApplication(sys.argv)window = FileTimeModifier()window.show()sys.exit(app.exec_())