We are culture science and a quest for design lorem ipsum dolor sit amet, consectetur adipiscing elit.

Date-Fixer-Script

The Architecture of Micro-Automation: Why Seconds Matter

The Compound Efficiency Problem

A script that automatically updates filenames with today’s date saves maybe 10-15 seconds per file. Trivial, right? Wrong.

I believe 70% of most business activities are wasted time and effort, primarily because we’ve failed to integrate automation into our daily workflows. We’ve built magnificent cathedral systems—databases, APIs, cloud infrastructure—but we’re still manually typing dates into filenames like digital peasants.

My philosophy: reduce administrative overhead to the bare minimum without becoming completely dependent on AI for menial tasks. This is where “vibe coding” excels—quick, practical solutions that eliminate friction from daily workflows.

When you architect hundreds of these micro-optimizations across all activities, those seconds compound into transformational efficiency gains. Like Christopher Alexander’s Pattern Language, each small automation forms part of a larger, more liveable digital environment.

Architectural Principles

1. Invisible Infrastructure

The best automation is invisible. Like well-designed architecture, users shouldn’t think about the underlying systems—they should just work. No popups, no confirmations, no cognitive overhead.

2. Compositional Design

Small, focused tools that compose well with existing workflows. The filename script integrates with Windows Explorer through the “Send To” menu, becoming part of the natural file management architecture rather than requiring new behavioral patterns.

3. Fault-Tolerant Systems

Like resilient building design, the script handles edge cases gracefully:

  • Multiple date formats (YYYY-MM-DD, DD-MM-YYYY, compact formats)
  • Date placeholders vs. existing dates
  • Filename conflicts and duplicate resolution
  • Both files and folders with unified logic

4. Progressive Enhancement

Start with a foundation, add complexity only when justified. The script evolved from basic date insertion to sophisticated pattern recognition, but each layer built on solid architectural principles.

The Implementation Architecture

The core system uses a layered approach:

Detection Layer:

Transformation Layer:

# Smart pattern recognition with validation
def is_valid_date_format(self, date_str):
    # Distinguishes real dates from random numbers
    # Handles YYYYMMDD vs DDMMYYYY disambiguation
    
def find_date_pattern(self, filename):
    # Hierarchical pattern matching
    # Placeholder detection before date detection
# Surgical replacement using match positions
new_name = name_without_ext[:match.start()] + self.today_date + name_without_ext[match.end():]

Integration Layer:

# Windows ecosystem integration
def create_send_to_entry(script_path):
    # Seamless Explorer integration
    # Silent execution via pythonw.exe

This architecture follows the Unix philosophy: do one thing well, compose with other tools, handle edge cases gracefully.

The Mathematics of Marginal Gains

Individual Level:

  • 20 files/day × 10 seconds = 3.3 minutes saved daily
  • 250 working days = 13.75 hours annually reclaimed
  • At $50/hour = $687.50 value per person per year

Team Level (10 people):

  • $6,875 in productivity annually
  • 137.5 hours of cognitive overhead eliminated
  • Improved filename hygiene across all projects

Organizational Architecture: When applied systematically across hundreds of micro-inefficiencies, you’re essentially re-architecting how humans interact with digital systems. Like urban planning, small improvements in individual interactions create dramatically different experiences at scale.

Vibe Coding as Architectural Practice

Traditional software architecture follows formal processes—requirements, design, implementation, testing. Vibe coding treats code like rapid architectural sketching:

  • Immediate deployment: Build in the actual context of use
  • User-driven evolution: Let real usage patterns drive design decisions
  • Good enough is perfect: Avoid over-engineering until complexity is justified
  • Compositional thinking: Each tool should enhance the broader workflow ecosystem

The filename script embodies this approach—it started as a rough sketch to solve a daily annoyance and evolved into a robust system through real-world usage.

Scaling the Architecture

Individual automations are like well-designed doorways—barely noticeable when done right, but fundamentally improving the experience of moving through space. When you systematically apply this thinking:

  • Email templates become architectural elements of communication flow
  • Keyboard shortcuts form the circulation patterns of digital work
  • Smart clipboard managers create efficient material handling systems
  • Automated project structures establish consistent spatial organization

Each automation is small, but collectively they architect a fundamentally different relationship between humans and their digital environment.

Implementation

The final system handles multiple date formats, placeholders, copy cleanup, files and folders, conflict resolution, and silent Windows integration.

Installation:

python date_filename_updater.py --install

Usage: Select files/folders → Right-click → Send to → “A_DATE_FIXER”

Conclusion: Digital Spatial Design

Like Christopher Alexander’s timeless architecture, effective automation should feel natural and inevitable. The goal isn’t to automate everything—it’s to architect digital environments where the most common actions flow effortlessly.

When 70% of knowledge work consists of navigating poorly designed processes, the opportunity for architectural intervention is enormous. Start with filenames. Then architect everything else.

Because in a world where everyone else is manually typing dates into filenames, the person who redesigned that interaction has already won.

#!/usr/bin/env python3
"""
==============================================================================
Date Filename Updater - SEND TO VERSION
==============================================================================
Silent file renaming tool that integrates with Windows Send To menu.

Features:
- Silent file processing via Send To menu
- Updates filenames with today's date
- Removes "- copy" and numbered duplicates
- Handles filename conflicts automatically
- Completely silent operation - no popups or dialogs

Usage:
1. python date_filename_updater.py --install
2. Select files in Explorer → Right-click → Send to → "Update Date in Filename"
3. Files are renamed silently in background
4. Disclaimer: The code provided here is for informational purposes only and is provided "as is", without warranty of any kind. Use at your own risk.

Requirements: Python 3.6+ only (no additional dependencies)
==============================================================================
"""

import os
import sys
import re
import argparse
from datetime import datetime
from pathlib import Path


class DateFilenameUpdater:
    def __init__(self):
        self.today_date = datetime.now().strftime("%d-%m-%Y")
        
        # Date placeholder patterns (DD/MM/YYYY, DD-MM-YYYY, etc.)
        self.placeholder_patterns = [
            r'YYYY[/\-_]MM[/\-_]DD',    # YYYY-MM-DD format
            r'DD[/\-_]MM[/\-_]YYYY',
            r'DD[/\-_]MM[/\-_]YY',
            r'DDMMYYYY',
            r'DDMMYY'
        ]
        
        # Existing date patterns - ORDER MATTERS! Most specific first
        self.date_patterns = [
            # 4-digit year formats (most specific first)
            r'\d{4}[/\-_]\d{1,2}[/\-_]\d{1,2}',   # YYYY-MM-DD, YYYY-M-D etc
            r'\d{1,2}[/\-_]\d{1,2}[/\-_]\d{4}',   # DD-MM-YYYY, D-M-YYYY etc
            # 2-digit year formats
            r'\d{2}[/\-_]\d{1,2}[/\-_]\d{1,2}',   # YY-MM-DD, YY-M-D etc (could be ambiguous)
            r'\d{1,2}[/\-_]\d{1,2}[/\-_]\d{2}',   # DD-MM-YY, D-M-YY etc
            # Compact formats (8 digits could be YYYYMMDD or DDMMYYYY)
            r'\d{8}',  # DDMMYYYY or YYYYMMDD - needs special handling
            r'\d{6}'   # DDMMYY or YYMMDD - needs special handling
        ]
    
    def clean_copy_duplicates(self, filename):
        """Remove '- copy' and numbered duplicates from filename"""
        name, ext = os.path.splitext(filename)
        
        # Check for copy/duplicate patterns
        copy_pattern = r'( - copy(?:\s*\(\d+\))?$|(?:\s*\(\d+\))$)'
        copy_match = re.search(copy_pattern, name)
        
        if copy_match:
            # Remove the copy pattern
            cleaned_name = name[:copy_match.start()]
            return cleaned_name + ext, True
        
        return filename, False
    
    def is_valid_date_format(self, date_str):
        """Check if a matched string is likely a valid date"""
        # Remove separators to get just digits
        digits_only = re.sub(r'[/\-_]', '', date_str)
        
        if len(digits_only) == 8:
            # Could be YYYYMMDD or DDMMYYYY
            # Check if first 4 digits look like a year (1900-2099)
            first_four = digits_only[:4]
            if first_four.isdigit() and 1900 <= int(first_four) <= 2099:
                # Likely YYYYMMDD format
                month = digits_only[4:6]
                day = digits_only[6:8]
                return month.isdigit() and day.isdigit() and 1 <= int(month) <= 12 and 1 <= int(day) <= 31
            else:
                # Likely DDMMYYYY format
                day = digits_only[:2]
                month = digits_only[2:4]
                year = digits_only[4:8]
                return (day.isdigit() and month.isdigit() and year.isdigit() and 
                       1 <= int(day) <= 31 and 1 <= int(month) <= 12 and 1900 <= int(year) <= 2099)
        
        elif len(digits_only) == 6:
            # Could be YYMMDD or DDMMYY - harder to distinguish
            # We'll assume DD-MM-YY format is more common
            return True
        
        # For separated formats, do basic range checks
        parts = re.split(r'[/\-_]', date_str)
        if len(parts) == 3:
            try:
                nums = [int(p) for p in parts]
                # Check for YYYY-MM-DD format (year first)
                if len(parts[0]) == 4 and 1900 <= nums[0] <= 2099:
                    return 1 <= nums[1] <= 12 and 1 <= nums[2] <= 31
                # Check for DD-MM-YYYY format (year last)
                elif len(parts[2]) == 4 and 1900 <= nums[2] <= 2099:
                    return 1 <= nums[0] <= 31 and 1 <= nums[1] <= 12
                # 2-digit year formats
                else:
                    return all(1 <= n <= 31 for n in nums)  # Basic range check
            except ValueError:
                return False
        
        return True
    
    def find_date_pattern(self, filename):
        """Find existing date patterns in filename"""
        name_without_ext = os.path.splitext(filename)[0]
        
        # Check placeholders first
        for pattern in self.placeholder_patterns:
            match = re.search(pattern, name_without_ext, re.IGNORECASE)
            if match:
                return pattern, 'placeholder', match
        
        # Check existing dates - try each pattern in order
        for pattern in self.date_patterns:
            matches = list(re.finditer(pattern, name_without_ext))
            for match in matches:
                matched_text = match.group()
                if self.is_valid_date_format(matched_text):
                    return pattern, 'date', match
        
        return None, None, None
    
    def update_filename(self, original_path):
        """Update a single filename or folder name with today's date"""
        try:
            directory = os.path.dirname(original_path)
            original_name = os.path.basename(original_path)
            
            # Check if it's a file or folder
            is_file = os.path.isfile(original_path)
            is_folder = os.path.isdir(original_path)
            
            if not (is_file or is_folder):
                return {
                    'success': False,
                    'old_name': original_name,
                    'new_name': None,
                    'error': 'Path is neither a file nor a folder'
                }
            
            # Clean copy duplicates first
            cleaned_name, copy_removed = self.clean_copy_duplicates(original_name)
            
            if is_file:
                # For files, separate name and extension
                name_without_ext, ext = os.path.splitext(cleaned_name)
            else:
                # For folders, treat the whole name as the "name without extension"
                name_without_ext = cleaned_name
                ext = ""
            
            # Find date patterns
            pattern, pattern_type, match = self.find_date_pattern(cleaned_name)
            
            if pattern and match:
                # Replace existing date or placeholder
                if pattern_type == 'placeholder':
                    # Replace the specific matched placeholder
                    new_name = name_without_ext[:match.start()] + self.today_date + name_without_ext[match.end():]
                else:
                    # Replace the specific matched date
                    new_name = name_without_ext[:match.start()] + self.today_date + name_without_ext[match.end():]
            else:
                # No date found, append today's date
                new_name = f"{name_without_ext} - {self.today_date}"
            
            new_full_name = new_name + ext
            new_path = os.path.join(directory, new_full_name)
            
            # Handle filename/folder name conflicts
            counter = 1
            while os.path.exists(new_path) and new_path != original_path:
                conflict_name = f"{new_name} ({counter})"
                new_full_name = conflict_name + ext
                new_path = os.path.join(directory, new_full_name)
                counter += 1
            
            # Rename the file/folder if the name changed
            if new_path != original_path:
                os.rename(original_path, new_path)
                return {
                    'success': True,
                    'old_name': original_name,
                    'new_name': new_full_name,
                    'copy_removed': copy_removed,
                    'type': 'file' if is_file else 'folder'
                }
            else:
                return {
                    'success': True,
                    'old_name': original_name,
                    'new_name': original_name,
                    'copy_removed': False,
                    'no_change': True,
                    'type': 'file' if is_file else 'folder'
                }
                
        except Exception as e:
            return {
                'success': False,
                'old_name': os.path.basename(original_path),
                'new_name': None,
                'error': str(e)
            }
    
    def process_files(self, file_paths):
        """Process multiple files and folders silently"""
        results = []
        for path in file_paths:
            if os.path.isfile(path) or os.path.isdir(path):
                result = self.update_filename(path)
                results.append(result)
        return results


def create_send_to_entry(script_path):
    """Create Send To menu entry for Windows"""
    try:
        # Get the Send To folder path
        sendto_path = os.path.join(
            os.path.expanduser("~"), 
            "AppData", "Roaming", "Microsoft", "Windows", "SendTo"
        )
        
        # Create the shortcut file path
        shortcut_path = os.path.join(sendto_path, "A_DATE_FIXER.lnk")
        
        # Try to use Windows COM objects for shortcut creation
        try:
            from win32com.client import Dispatch
            
            shell = Dispatch('WScript.Shell')
            shortcut = shell.CreateShortCut(shortcut_path)
            
            # Use pythonw.exe if available for silent execution
            python_exe = sys.executable
            if python_exe.endswith('python.exe'):
                pythonw_exe = python_exe.replace('python.exe', 'pythonw.exe')
                if os.path.exists(pythonw_exe):
                    python_exe = pythonw_exe
            
            shortcut.Targetpath = python_exe
            shortcut.Arguments = f'"{script_path}"'
            shortcut.WorkingDirectory = os.path.dirname(script_path)
            shortcut.Description = "A_DATE_FIXER - Update filename with today's date"
            shortcut.IconLocation = "shell32.dll,70"
            shortcut.save()
            
            print(f"✓ Created Send To entry: {shortcut_path}")
            return True
            
        except ImportError:
            # Fallback: Create a batch file instead
            batch_path = os.path.join(sendto_path, "A_DATE_FIXER.bat")
            
            # Use pythonw.exe if available for silent execution
            python_exe = sys.executable
            if python_exe.endswith('python.exe'):
                pythonw_exe = python_exe.replace('python.exe', 'pythonw.exe')
                if os.path.exists(pythonw_exe):
                    python_exe = pythonw_exe
            
            batch_content = f'''@echo off
"{python_exe}" "{script_path}" %*
'''
            
            with open(batch_path, 'w') as f:
                f.write(batch_content)
            
            print(f"✓ Created Send To batch file: {batch_path}")
            print("  (Note: Install pywin32 for better .lnk shortcut creation)")
            return True
            
    except Exception as e:
        print(f"❌ Error creating Send To entry: {e}")
        return False


def remove_send_to_entry():
    """Remove Send To menu entries"""
    try:
        sendto_path = os.path.join(
            os.path.expanduser("~"), 
            "AppData", "Roaming", "Microsoft", "Windows", "SendTo"
        )
        
        # Remove both .lnk and .bat versions
        files_to_remove = [
            "A_DATE_FIXER.lnk",
            "A_DATE_FIXER.bat"
        ]
        
        removed_count = 0
        for filename in files_to_remove:
            file_path = os.path.join(sendto_path, filename)
            if os.path.exists(file_path):
                os.remove(file_path)
                print(f"✓ Removed: {file_path}")
                removed_count += 1
        
        if removed_count > 0:
            print(f"✓ Successfully removed {removed_count} Send To entries")
            return True
        else:
            print("! No Send To entries found to remove")
            return False
            
    except Exception as e:
        print(f"❌ Error removing Send To entries: {e}")
        return False


def install():
    """Install the Send To menu entry"""
    script_path = os.path.abspath(__file__)
    
    print("Date Filename Updater - Send To Installation")
    print("=" * 50)
    print(f"Script location: {script_path}")
    print("")
    
    # Create the main Send To entry
    success = create_send_to_entry(script_path)
    
    if success:
        print("\n🎉 SUCCESS! Send To menu integration created!")
        print("\n📁 SEND TO MENU USAGE:")
        print("   1. Select one or more files in Windows Explorer")
        print("   2. Right-click → Send to → 'A_DATE_FIXER'")
        print("   3. Files are renamed silently with today's date")
        print("")
        print("✨ FEATURES:")
        print("   • Silent operation - no popups or confirmations")
        print("   • Handles multiple files and folders at once")
        print("   • Removes '- copy' and numbered duplicates automatically")
        print("   • Updates existing dates or adds new dates")
        print("   • Resolves filename conflicts automatically")
        print("   • Supports YYYY-MM-DD, DD-MM-YYYY, and other date formats")
        print("")
        print("📋 WHAT HAPPENS:")
        print("   FILES:")
        print("   • Report - copy.pdf → Report - 09-06-2025.pdf")
        print("   • Meeting_06-06-25.docx → Meeting_09-06-2025.docx")
        print("   • Notes.txt → Notes - 09-06-2025.txt")
        print("   • Budget_DD-MM-YYYY.xlsx → Budget_09-06-2025.xlsx")
        print("   • Project_2024-03-15.pdf → Project_09-06-2025.pdf")
        print("   • Report_2025-01-15.docx → Report_09-06-2025.docx")
        print("   FOLDERS:")
        print("   • Meeting Minutes_YYYY-MM-DD → Meeting Minutes_09-06-2025")
        print("   • Project_2024-03-15 → Project_09-06-2025")
        print("   • Archive - copy → Archive - 09-06-2025")
        print("")
        print("🗑️  TO UNINSTALL:")
        print(f"   python {os.path.basename(script_path)} --uninstall")
    
    return success


def uninstall():
    """Uninstall the Send To menu entry"""
    print("Date Filename Updater - Send To Uninstallation")
    print("=" * 50)
    
    success = remove_send_to_entry()
    
    if success:
        print("\n✓ Send To menu integration removed successfully!")
    else:
        print("\n! Nothing to uninstall")
    
    return success


def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(
        description="Update filenames with today's date via Send To menu",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python date_filename_updater.py --install
  python date_filename_updater.py --uninstall
  python date_filename_updater.py file1.txt file2.pdf
        """
    )
    
    parser.add_argument(
        'files', 
        nargs='*', 
        help='Files and folders to process (used by Send To menu)'
    )
    parser.add_argument(
        '--install', 
        action='store_true', 
        help='Install Send To menu entry'
    )
    parser.add_argument(
        '--uninstall', 
        action='store_true', 
        help='Remove Send To menu entry'
    )
    
    args = parser.parse_args()
    
    # Handle installation
    if args.install:
        install()
        return
    
    # Handle uninstallation
    if args.uninstall:
        uninstall()
        return
    
    # Handle file processing (called by Send To menu)
    if args.files:
        updater = DateFilenameUpdater()
        updater.process_files(args.files)
        return
    
    # No arguments - show help
    print("\nDate Filename Updater - Send To Version")
    print("======================================")
    print("")
    print("INSTALLATION:")
    print("python date_filename_updater.py --install")
    print("")
    print("USAGE:")
    print("1. Select files and/or folders in Windows Explorer")
    print("2. Right-click → Send to → 'A_DATE_FIXER'")
    print("3. Files and folders renamed silently with today's date")
    print("")
    print("UNINSTALL:")
    print("python date_filename_updater.py --uninstall")
    print("")
    print("FEATURES:")
    print("• Silent operation (no popups)")
    print("• Works with multiple files and folders")
    print("• Removes copy duplicates automatically")
    print("• Updates existing dates (including YYYY-MM-DD format)")
    print("• No dependencies required")
    print("")


if __name__ == "__main__":
    main()

Leave a comment

You don't have permission to register