import os import glob import subprocess from datetime import datetime, timedelta def set_file_timestamps(file_path, dt): """Sets Creation, Write, and Access time for a file on Windows using PowerShell.""" # Ensure absolute path with backslashes for PowerShell abs_path = os.path.abspath(file_path) # Format: MM/DD/YYYY HH:MM:SS AM/PM ts_str = dt.strftime('%m/%d/%Y %I:%M:%S %p') # We use Get-Item and set the properties. This covers CreationTime which Python's os.utime lacks. ps_cmd = ( f"$f = Get-Item -LiteralPath '{abs_path}'; " f"$f.CreationTime = '{ts_str}'; " f"$f.LastWriteTime = '{ts_str}'; " f"$f.LastAccessTime = '{ts_str}';" ) try: subprocess.run(["powershell", "-Command", ps_cmd], check=True, capture_output=True) except subprocess.CalledProcessError as e: print(f"Error setting timestamp for {file_path}: {e.stderr.decode().strip()}") def main(): print("Starting improved rename and timestamp synchronization (1-day increments)...") # Find all mp3 files in the current directory mp3_files = glob.glob("*.mp3") # Keep only files that start with 3 digits to_process = [] for f in mp3_files: if len(f) > 3 and f[:3].isdigit(): to_process.append(f) # Sort them to maintain current numerical/alphabetical order to_process.sort() # Base date: Jan 1st of the current year current_dt = datetime(datetime.now().year, 1, 1, 12, 0, 0) # First pass: Rename to temporary names to avoid collisions (e.g. 025 to 020 failing if 020 exists) temp_renames = [] count = 10 for old_name in to_process: new_name = f"{count:03d}{old_name[3:]}" if old_name != new_name: temp_name = f"temp_{count:03d}_{old_name}" os.rename(old_name, temp_name) temp_renames.append((temp_name, new_name)) else: temp_renames.append((old_name, new_name)) count += 10 # Second pass: Finalize names and set timestamps # Reset count and date for the second pass current_dt = datetime(datetime.now().year, 1, 1, 12, 0, 0) for temp_name, final_name in temp_renames: if temp_name != final_name: print(f"Renaming: {temp_name} -> {final_name}") os.rename(temp_name, final_name) print(f"Setting timestamp (Day {current_dt.strftime('%m/%d')}): {final_name}") set_file_timestamps(final_name, current_dt) # Increment by 1 day current_dt += timedelta(days=1) if __name__ == "__main__": main() print("\nProcessing complete!")