Thursday, January 30, 2025

DATE Chnaging python script

 I had a bunch of files that I smartly named by using a date format of DAY / MONTH / YEAR. The format was this "22_12_2025_" .
Except when you put them into name order, they get sorted by days first in a hectic monthly and yearly order and not by year and month, then day. Here is a python script to sort out this basic issue.

 
```python


import os
import re

# Path to the folder containing the documents
directory = "/home/levi/Documents/date"

# Function to convert date format from DD_MM_YYYY to YYYY_MM_DD
def convert_date_format(filename):
    # Use a regex to match the date pattern at the start of the filename
    match = re.match(r"(\d{2})_(\d{2})_(\d{4})_", filename)
    if match:
        day, month, year = match.groups()
        # Reformat to YYYY_MM_DD
        new_date = f"{year}_{month}_{day}_"
        return filename.replace(match.group(0), new_date)
    return filename

# Iterate over each file in the directory
for filename in os.listdir(directory):
    old_path = os.path.join(directory, filename)
    
    # Skip directories and only process files
    if os.path.isfile(old_path):
        new_filename = convert_date_format(filename)
        new_path = os.path.join(directory, new_filename)
        
        # Rename the file if the name has changed
        if old_path != new_path:
            os.rename(old_path, new_path)
            print(f"Renamed: {filename} -> {new_filename}")
```

No comments:

Post a Comment

Sharepoint sync and lock issues - solutions

 Sharepoint synced down to your PC by onedrive can have a ton of errors. It is caused by the simple dis-functionality of this badly thought ...