SoFunction
Updated on 2025-04-13

Python implements batch modification of file dates

1. Introduction

In daily work and study, we often need to modify the date of the file creation or modification. For example, in order to organize photos, documents or other files, we need to modify the date of the file to the actual shooting or creation date. If you do these operations manually, it will not only be time-consuming and labor-intensive, but also prone to errors. Therefore, it is especially important to write a batch file date modifier. This article will explain how to write a batch file date modifier in Python, which can modify the creation or modification date of a file.

2. Principles of batch file date modifier

The core principle of the batch file date modifier is to iterate through all files in the specified directory, get the creation or modification date of each file, and then modify the creation or modification date of the file according to the new date entered by the user. In this process, we need to consider the following issues:

  • How to iterate through all files in a specified directory?
  • How to get the date of creation or modification of a file?
  • How to modify the creation or modification date of a file?

Next, we will introduce solutions to these three problems separately.

3. Design of batch file date modifier

When designing a batch file date modifier, we need to consider the following aspects:

User interface: In order to facilitate users to use, we can design a simple command line interface, allowing users to enter parameters such as directory, new date, etc.

Date Getting: We need to write a date getter that gets the date of creation or modification of the file.

Date Modification: We need to write a date modifier to modify the creation or modification date of the file.

IV. Implementation of batch file date modifier

Next, we will introduce the implementation process of batch file date modifier in detail. For convenience, we will write this tool in Python.

user interface

We can use Python's argparse library to design a simple command line interface. The interface includes the following parts:

  • Directory parameters: Let the user specify the directory where the file that needs to be modified date is located.
  • Date parameter: Let the user specify a new date.
  • Date type parameter: Let the user specify the date type (create date or modified date) that needs to be modified.

Date Getting

We can use Python's() and() functions to get the file's modification date and creation date. The specific implementation is as follows:

import os
def get_file_dates(file_path):
    modification_time = (file_path)
    creation_time = (file_path)
    return modification_time, creation_time

Date modification

We can use Python's() function to modify the file creation or modification date. The specific implementation is as follows:

import os
import datetime
def set_file_date(file_path, new_date, date_type):
    if date_type == 'modification':
        (file_path, (new_date, new_date))
    elif date_type == 'creation':
        (file_path, (new_date, (file_path)))
    else:
        raise ValueError("Invalid date type. Must be 'modification' or 'creation'.")

5. Complete code example

import argparse
import os
import datetime
def get_file_dates(file_path):
    modification_time = (file_path)
    creation_time = (file_path)
    return modification_time, creation_time
def set_file_date(file_path, new_date, date_type):
    if date_type == 'modification':
        (file_path, (new_date, new_date))
    elif date_type == 'creation':
        (file_path, (new_date, (file_path)))
    else:
        raise ValueError("Invalid date type. Must be 'modification' or 'creation'.")
def main():
    parser = (description="Batch File Date Modifier")
    parser.add_argument("directory", help="Specify Directory")
    parser.add_argument("new_date", help="New date (YYYY-MM-DD HH:MM:SS)")
    parser.add_argument("date_type", help="Date Type (modification or creation)")
    args = parser.parse_args()
    dir_path = 
    new_date = (args.new_date, "%Y-%m-%d %H:%M:%S")
    new_timestamp = int(new_date.timestamp())
    date_type = args.date_type
    file_list = [f for f in (dir_path) if ((dir_path, f))]
    for file_name in file_list:
        file_path = (dir_path, file_name)
        modification_time, creation_time = get_file_dates(file_path)
        print(f"File: {file_path}")
        print(f"  Modification time: {(modification_time)}")
        print(f"  Creation time: {(creation_time)}")
        if date_type == 'modification':
            set_file_date(file_path, new_timestamp, 'modification')
        elif date_type == 'creation':
            set_file_date(file_path, new_timestamp, 'creation')
        print(f"  New date set to: {(new_timestamp)}")
        print()
if __name__ == "__main__":
    main()

6. Supplementary method

1. Use the python three-party library win32file API operation file date

from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time # You can ignore this Time error (it is still OK to run the program)import time


def modifyFileTime(filePath, createTime, modifyTime, accessTime, offset):
  """
   Used to modify the relevant time attributes of any file, time format: YYYY-MM-DD HH:MM:SS For example: 2019-02-02 00:01:02
   :param filePath: file path name
   :param createTime: Created time
   :param modifyTime: ModifyTime
   :param accessTime: Access time
   :param offset: The number of seconds of time offset, tuple format, order and parameter time corresponds to
   """
  try:
    format = "%Y-%m-%d %H:%M:%S" # Time format    cTime_t = timeOffsetAndStruct(createTime, format, offset[0])
    mTime_t = timeOffsetAndStruct(modifyTime, format, offset[1])
    aTime_t = timeOffsetAndStruct(accessTime, format, offset[2])

    fh = CreateFile(filePath, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, 0)
    createTimes, accessTimes, modifyTimes = GetFileTime(fh)

    createTimes = Time((cTime_t))
    accessTimes = Time((aTime_t))
    modifyTimes = Time((mTime_t))
    SetFileTime(fh, createTimes, accessTimes, modifyTimes)
    CloseHandle(fh)
    return 0
  except:
    return 1


def timeOffsetAndStruct(times, format, offset):
  return (((times, format)) + offset)


if __name__ == '__main__':
  # Need to configure it yourself  cTime = "2019-12-13 21:51:02" # Create time  mTime = "2019-02-02 00:01:03" # Modify time  aTime = "2019-02-02 00:01:04" # Visit time  fName = r"E:\test_pro\fileOperate\" # File path, the file exists before it succeeds (can write absolute paths or relative paths)
  offset = (0, 1, 2) # Number of seconds offset (I don't know what to do)
  # Call the function to modify the file creation time and determine whether the modification is successful  r = modifyFileTime(fName, cTime, mTime, aTime, offset)
  if r == 0:
    print('Modification is completed')
  elif r == 1:
    print('Modification failed')

The modification time of batch modification file is the current time

#Change the folder to modify the time to the current timeimport os
path = r"" #Folder Directory 
def changeDay(path): #Write a character at the end and delete it    with open(path, "a") as f:
        ("1")
    with open(path, "rb+") as f:
        (-1, os.SEEK_END)
        ()
 
def getAlldirInDiGui(path):
    filesList=(path) #List all files in the current path    print(filesList)
 
    for fileName in filesList: #Travel all files in the current path        fileAbpath=(path,fileName)
        if (fileAbpath): #If it's a directory            #print("Directory:" ,fileName)            getAlldirInDiGui(fileAbpath)
        else:
            #print("ordinary file",fileName)            changeDay(fileAbpath)
 
getAlldirInDiGui(path)

3. Bulk modification time

With the acquisition of file time information, we can start batch modifying the file time. In Python, we can use the() function to modify the timestamp of a file. The () function accepts two parameters, the first parameter is the file path, and the second parameter is a tuple containing new timestamp information.

Here is a sample code for batch modifying files:

import os
import time

folder_path = 'path/to/folder'
files = (folder_path)

for file in files:
    file_path = (folder_path, file)
    new_time = ()  # Get the current time as a new time stamp    (file_path, (new_time, new_time))

The above code will modify the timestamps of all files in the specified folder to the current time. You can modify the folder_path variable according to actual needs to specify the folder path to the time you need to modify.

The above is the detailed content of Python's implementation of batch modification of file dates. For more information about Python's modification of file dates, please pay attention to my other related articles!