Python实现修改文件创建时间(支持任意时间修改)

 更新时间:2025年07月01日 09:30:22   作者:JHC000000  
这篇文章主要为大家详细介绍了如何使用Python实现修改文件创建时间,可以支持任意时间修改,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

前言

本文主要来和大家介绍一个Python脚本,用于修改文件的创建时间和系统时间

主要通过change_file_creation_time和change_system_times函数实现,同时演示了如何使用ctypes库来操作系统时间

完整代码如下

# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: change_files_times.py
@time: 2023/11/22 11:55 
@desc: 

"""

import os
import time
import ctypes


def parse_date(date):
    """
    2023-12-12 12:12:12 解析时间
    """
    head,tail = date.split(" ")
    year,month,day = head.split("-")
    hour,min,sec = tail.split(":")
    return year,month,day,hour,min,sec


def change_file_creation_time(file_path, year,month,day,hour,min,sec):
    """
	修改文件更改时间
    """
    new_creation_time = time.mktime((int(year), int(month), int(day), int(hour), int(min), int(sec), 0, 0, 0))
    # 获取文件的修改时间和访问时间
    access_time = os.path.getatime(file_path)
    modified_time = os.path.getmtime(file_path)

    # 修改文件的修改时间
    os.utime(file_path, (access_time, new_creation_time))





def change_system_times(year,month,day,hour,min,sec,msec="0"):
    """
	调用系统接口更改系统时间,隔一段时间系统时钟会自动更新回当前真实时间
    """
    # 定义 SYSTEMTIME 结构体
    class SYSTEMTIME(ctypes.Structure):
        _fields_ = [
            ('wYear', ctypes.c_ushort),
            ('wMonth', ctypes.c_ushort),
            ('wDayOfWeek', ctypes.c_ushort),
            ('wDay', ctypes.c_ushort),
            ('wHour', ctypes.c_ushort),
            ('wMinute', ctypes.c_ushort),
            ('wSecond', ctypes.c_ushort),
            ('wMilliseconds', ctypes.c_ushort)
        ]

    # 设置目标日期
    target_date = SYSTEMTIME(
        wYear=int(year),
        wMonth=int(month),
        wDayOfWeek=0,  # 这里可以忽略,程序会自动填充正确的值
        wDay=int(day),
        wHour=int(hour)-8,
        wMinute=int(min),
        wSecond=int(sec),
        wMilliseconds=int(msec)
    )

    # 调用 SetSystemTime 函数设置系统日期
    ctypes.windll.kernel32.SetSystemTime(ctypes.byref(target_date))

def cp_files(file,out_path):
    """
	复制文件,实现更改文件创建时间
    """
    name = os.path.split(file)[-1]
    save_file = os.path.join(out_path,name)
    with open(file,"rb")as fp,\
    open(save_file,"wb")as fp2:
        fp2.write(fp.read())
    return save_file

def main(create_time,change_time,in_file,out_path):
	"""
	处理流程
	"""
    year, month, day, hour, min, sec = parse_date(create_time)
    change_system_times(year, month, day, hour, min, sec)
    save_file = cp_files(in_file,out_path)
    year, month, day, hour, min, sec = parse_date(change_time)
    change_file_creation_time(save_file, year,month,day,hour,min,sec)





if __name__ == '__main__':
	# 备注:程序运行必须获取管理员权限,否则,修改文件创建时间将失败
    in_file = input("请输入要修改文件路径:")
    out_path = input("请输入更改时间后文件保存路径:")
    create_time = input("请输入文件创建时间:[2023-12-12 12:12:12]")
    change_time = input("请输入文件修改时间:[2023-12-12 12:12:12]")

    # in_file = R"D:\Desktop\miniblink-20230412\更新日志.txt"
    # out_path = R"D:\Desktop"
    # create_time = "2020-12-12 12:12:12"
    # change_time = "2021-12-12 12:12:12"

    main(create_time,change_time,in_file,out_path)

方法补充

使用Python批量修改文件修改时间

示例如下

import os
import sys
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,
                             QWidget, QLabel, QComboBox, QDateTimeEdit, QPushButton,
                             QFileDialog, QCheckBox, QScrollArea, QGroupBox)
from PyQt5.QtCore import QDateTime, Qt
 
 
class FileTimeModifier(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("文件修改时间批量修改工具")
        self.setGeometry(100, 100, 800, 600)
 
        # 主部件和布局
        self.main_widget = QWidget()
        self.main_layout = QVBoxLayout()
 
        # 顶部控制区域
        self.control_group = QGroupBox("控制面板")
        self.control_layout = 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.control_layout.addWidget(self.add_button)
        self.control_layout.addWidget(self.select_all_checkbox)
        self.control_layout.addWidget(self.modify_button)
        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())
 
        # 添加到布局
        entry_layout.addWidget(checkbox)
        entry_layout.addWidget(file_label)
        entry_layout.addWidget(time_edit)
        entry_widget.setLayout(entry_layout)
 
        # 保存条目信息
        self.file_entries.append({
            'widget': entry_widget,
            'checkbox': checkbox,
            'filename': filename,
            'time_edit': time_edit
        })
 
        # 添加到滚动区域
        self.scroll_layout.addWidget(entry_widget)
 
    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 = 0
 
        for entry in self.file_entries:
            if entry['checkbox'].isChecked():
                filepath = os.path.join(current_dir, entry['filename'])
                new_time = entry['time_edit'].dateTime().toPyDateTime()
 
                # 转换为时间戳
                timestamp = new_time.timestamp()
 
                # 修改文件时间
                try:
                    os.utime(filepath, (timestamp, timestamp))
                    modified_count += 1
                except Exception as e:
                    print(f"修改文件 {entry['filename']} 时间失败: {e}")
 
        print(f"成功修改了 {modified_count} 个文件的修改时间")
 
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = FileTimeModifier()
    window.show()
    sys.exit(app.exec_())

以上就是Python实现修改文件创建时间(支持任意时间修改)的详细内容,更多关于Python修改文件时间的资料请关注脚本之家其它相关文章!

相关文章

  • python爬虫开发之urllib模块详细使用方法与实例全解

    python爬虫开发之urllib模块详细使用方法与实例全解

    这篇文章主要介绍了python爬虫开发之urllib模块详细使用方法与实例全解,需要的朋友可以参考下
    2020-03-03
  • python 5个实用的技巧

    python 5个实用的技巧

    这篇文章主要介绍了python 5个实用的技巧,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2020-09-09
  • 利用python爬取古诗文网中各类古诗的方法

    利用python爬取古诗文网中各类古诗的方法

    这篇文章主要介绍了利用python爬取古诗文网中各类古诗的方法,文中通过代码示例给大家介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-03-03
  • 基于Python实现图片九宫格切图程序

    基于Python实现图片九宫格切图程序

    这篇文章主要为大家详细介绍了如何利用python和C++代码实现图片九宫格切图程序,文中的示例代码讲解详细,具有一定的借鉴价值,需要的可以参考一下
    2023-04-04
  • Python Behave框架学习

    Python Behave框架学习

    behave是python语言的行为驱动开发,全称:Behavior-driven development,简称BDD,它是一种敏捷软件开发技术,它鼓励软件项目中的开发人员、QA和非技术或业务参与者之间进行协作,本文给大家介绍Python Behave框架,感兴趣的朋友一起看看吧
    2022-07-07
  • 解决django同步数据库的时候app models表没有成功创建的问题

    解决django同步数据库的时候app models表没有成功创建的问题

    今天小编就为大家分享一篇解决django同步数据库的时候app models表没有成功创建的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-08-08
  • 一文详解如何在Python中进行数学建模

    一文详解如何在Python中进行数学建模

    数学建模是数据科学中使用的强大工具,通过数学方程和算法来表示真实世界的系统和现象,本文将指导大家完成Python中的数学建模过程,感兴趣的可以了解下
    2024-11-11
  • 利用pyuic5将ui文件转换为py文件的方法

    利用pyuic5将ui文件转换为py文件的方法

    今天小编就为大家分享一篇利用pyuic5将ui文件转换为py文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • 使用python获取电脑的磁盘信息方法

    使用python获取电脑的磁盘信息方法

    今天小编就为大家分享一篇使用python获取电脑的磁盘信息方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-11-11
  • 用python画了个圣诞树给女朋友

    用python画了个圣诞树给女朋友

    大家好,本篇文章主要讲的是用python画了个圣诞树给女朋友,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2021-12-12

最新评论