import os import re import subprocess from datetime import datetime, timedelta def set_creation_date(file_path, creation_date): """ Set the creation date of a file. Parameters: - file_path: The path to the file. - creation_date: The desired creation date. The creation_date parameter should be a string in the format 'YYYY-MM-DD HH:MM:SS'. """ try: # Convert the creation date string to a datetime object creation_datetime = datetime.strptime(creation_date, '%Y-%m-%d %H %M %S') creation_datetime = creation_datetime + timedelta(days=18310, hours=19, minutes=34) # Get the timestamp from the datetime object for os.utime timestamp = creation_datetime.timestamp() # Get the string from the datetime object for SetFile timestring = creation_datetime.strftime("%m/%d/%Y %H:%M:%S") # Set the access/modification date using the os.utime function os.utime(file_path, (timestamp, timestamp)) # Set the creation date using the SetFile command subprocess.run(['SetFile', '-d', timestring, file_path]) print(f"Creation date set successfully for {file_path}") except Exception as e: print(f"Error setting creation date for {file_path}: {e}") def extract_creation_date_from_filename(filename): """ Extract the creation date from the filename. This assumes that the filename follows a specific format that includes the creation date. Modify the regular expression pattern as needed. """ pattern = r'(\d{4}-\d{2}-\d{2} \d{2} \d{2} \d{2})' match = re.search(pattern, filename) if match: return match.group(1) else: return None def process_files_in_folder(folder_path): """ Process all files in the specified folder. Parameters: - folder_path: The path to the folder containing the files. """ for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) # Check if the item in the folder is a file (not a subdirectory) if os.path.isfile(file_path): creation_date_from_filename = extract_creation_date_from_filename(filename) if creation_date_from_filename: set_creation_date(file_path, creation_date_from_filename) else: print(f"Creation date not found in the filename for {file_path}.") # Example usage: folder_path = '/Users/qin-yu/temp/' process_files_in_folder(folder_path)