I'm working on a simple Python script that backs up files.
While this is working fine, I want to add a feature where folders that have a name with 6 months back will automatically deleted.
Basicly if there would be a folder called: 2014-05-23 and I run the script it should be deleted.
Now the problem I'm having is with converting the string from the loop in a date (for time comparison).
import os
import shutil
import time
import datetime
root_folder = r'C:\Users\Coen\Desktop\Test 1'
bestemming = r'C:\Users\Coen\Desktop\test 2\\'
date_str = time.strftime("%Y-%m-%d")
nieuwe_map = os.path.join(bestemming + date_str)
verwijder_datum = (datetime.date.today() - datetime.timedelta(6*365/12))
shutil.copytree(root_folder, nieuwe_map)
**for oude_map, bestand, files in os.walk(bestemming):
if datetime.datetime.strptime((oude_map[-9:]), "%Y-%m-%d") > verwijder_datum:
shutil.rmtree(oude_map)**
I get value errors because some of the results can't be converted to strings. I tried working with except and try but I think I'm doing something wrong, cause I don't get it to work properly. I hope you guys can help me.
Summary: I need to convert filepaths into dates for python to decide wether or not to remove the folder. The Loop I'm using returns values that aren't convertable into dates, and I can't seem to fix it with a exception. How do I fix this?
Try the following:
for oude_map, bestand, files in os.walk(bestemming):
try:
if datetime.datetime.strptime((oude_map[-10:]), "%Y-%m-%d").date() < verwijder_datum:
shutil.rmtree(oude_map)
except ValueError:
pass