最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現(xiàn)修改文件創(chuàng)建時間(支持任意時間修改)

 更新時間:2025年07月01日 09:30:22   作者:JHC000000  
這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)修改文件創(chuàng)建時間,可以支持任意時間修改,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下

前言

本文主要來和大家介紹一個Python腳本,用于修改文件的創(chuàng)建時間和系統(tǒng)時間

主要通過change_file_creation_time和change_system_times函數(shù)實現(xiàn),同時演示了如何使用ctypes庫來操作系統(tǒng)時間

完整代碼如下

# !/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"):
    """
	調(diào)用系統(tǒng)接口更改系統(tǒng)時間,隔一段時間系統(tǒng)時鐘會自動更新回當前真實時間
    """
    # 定義 SYSTEMTIME 結(jié)構(gòu)體
    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)
        ]

    # 設(shè)置目標日期
    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)
    )

    # 調(diào)用 SetSystemTime 函數(shù)設(shè)置系統(tǒng)日期
    ctypes.windll.kernel32.SetSystemTime(ctypes.byref(target_date))

def cp_files(file,out_path):
    """
	復制文件,實現(xiàn)更改文件創(chuàng)建時間
    """
    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__':
	# 備注:程序運行必須獲取管理員權(quán)限,否則,修改文件創(chuàng)建時間將失敗
    in_file = input("請輸入要修改文件路徑:")
    out_path = input("請輸入更改時間后文件保存路徑:")
    create_time = input("請輸入文件創(chuàng)建時間:[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()
 
        # 頂部控制區(qū)域
        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("應(yīng)用修改")
        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)
 
        # 滾動區(qū)域用于文件列表
        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):
        """刷新當前目錄下的文件列表"""
        # 清空現(xiàn)有條目
        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))]
 
        # 為每個文件創(chuàng)建條目
        for file in files:
            self.add_file_entry(file)
 
    def add_file_entry(self, filename):
        """為單個文件創(chuàng)建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
        })
 
        # 添加到滾動區(qū)域
        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()
 
                # 轉(zhuǎn)換為時間戳
                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實現(xiàn)修改文件創(chuàng)建時間(支持任意時間修改)的詳細內(nèi)容,更多關(guān)于Python修改文件時間的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 一篇文章帶你入門python之推導式

    一篇文章帶你入門python之推導式

    這篇文章主要為大家詳細介紹了python的推導式,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02
  • Anaconda(miniconda)入門使用完全指南

    Anaconda(miniconda)入門使用完全指南

    Conda是一個管理版本和Python環(huán)境的工具,它使用起來非常容易,下面這篇文章主要給大家介紹了關(guān)于Anaconda(miniconda)入門使用的相關(guān)資料,文中介紹的非常詳細,需要的朋友可以參考下
    2023-02-02
  • Python 3 使用Pillow生成漂亮的分形樹圖片

    Python 3 使用Pillow生成漂亮的分形樹圖片

    這篇文章主要介紹了Python 3 使用Pillow生成漂亮的分形樹圖片,本文通過實例代碼介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-12-12
  • 單鏈表反轉(zhuǎn)python實現(xiàn)代碼示例

    單鏈表反轉(zhuǎn)python實現(xiàn)代碼示例

    這篇文章主要介紹了單鏈表反轉(zhuǎn)python實現(xiàn),分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • Python基礎(chǔ)之模塊詳解

    Python基礎(chǔ)之模塊詳解

    本文詳細講解了Python基礎(chǔ)之模塊,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • Python實現(xiàn)自動打開電腦應(yīng)用的示例代碼

    Python實現(xiàn)自動打開電腦應(yīng)用的示例代碼

    這篇文章主要介紹了Python實現(xiàn)自動打開電腦應(yīng)用的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-04-04
  • Python極簡代碼實現(xiàn)楊輝三角示例代碼

    Python極簡代碼實現(xiàn)楊輝三角示例代碼

    楊輝三角形因為其形式簡單,又有一定的使用價值,因此是入門編程題中被用的最多的,也是很好的語言實例標的。這篇文章就給大家介紹了Python極簡代碼實現(xiàn)楊輝三角的方法,文章給出了詳細的示例代碼和解釋,對大家理解很有幫助,感興趣的朋友們下面來一起看看吧。
    2016-11-11
  • Python字符和字符值(ASCII或Unicode碼值)轉(zhuǎn)換方法

    Python字符和字符值(ASCII或Unicode碼值)轉(zhuǎn)換方法

    這篇文章主要介紹了Python字符和字符值(ASCII或Unicode碼值)轉(zhuǎn)換方法,即把字符串在ASCII值或者Unicode值之間相與轉(zhuǎn)換的方法,需要的朋友可以參考下
    2015-05-05
  • pandas分區(qū)間,算頻率的實例

    pandas分區(qū)間,算頻率的實例

    今天小編就為大家分享一篇pandas分區(qū)間,算頻率的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python讀取csv文件指定行的2種方法詳解

    python讀取csv文件指定行的2種方法詳解

    這篇文章主要介紹了python讀取csv文件指定行的方法詳解,需要的朋友可以參考下
    2020-02-02

最新評論

六枝特区| 固镇县| 越西县| 章丘市| 三亚市| 克拉玛依市| 沅江市| 垣曲县| 临泉县| 长海县| 密山市| 南皮县| 叶城县| 永仁县| 三穗县| 茂名市| 通海县| 虎林市| 怀柔区| 大新县| 宝鸡市| 绍兴县| 景泰县| 麟游县| 邓州市| 长岭县| 方城县| 庄浪县| 蓬莱市| 万山特区| 灌阳县| 沽源县| 蒙城县| 惠州市| 九龙城区| 三明市| 丰顺县| 卢龙县| 木兰县| 瓦房店市| 盐边县|