I've got a kind of script in python in charge of deleting folders that are older than a given date. This is my code for doing it:
from pathlib import Path
from shutil import rmtree
import datetime
from datetime import datetime, timezone, timedelta
EXPIRATION_WEEKS=4
def delete_folder(folder: Path):
"""
Delete the content folder.
"""
rmtree(folder)
def check_expiration_date(folder: Path):
expiration_date = datetime.now(timezone.utc) - timedelta(weeks=EXPIRATION_WEEKS)
folder_date = folder.name.split('-')[0]
folder_date = datetime.strptime(folder_date, '%Y%m%d')
return True if folder_date.date() < expiration_date.date() else False
def check_content_folder(folder: Path):
"""
Check if the content folder has a concrete character
"""
return True if '-' in folder.name else False
def delete_folders_with_expired_date(data_path: Path):
"""
Delete the content folder.
"""
for folder in data_path.glob('*'):
if folder.is_dir():
if check_content_folder(folder):
if check_expiration_date(folder):
delete_folder(folder)
print(f"Deleted folder: {folder}")
else:
delete_folders_with_expired_date(folder)
The folder's name structure is as follows:
20220317-120259_.page_w_200-1.png
As you can see, the first part of the folder's name is the date (until '-' character).
I would like to check that the date at the beginning is consistent, i.e. that it is not a date like this:
- 10000101
- 28070405
Since the library in charge of formatting the string accepts this kind of date.
CodePudding user response:
This is exactly the solution I was searching, thanks to @BoarGules:
def validate_date(date_str: str):
"""
Validate if is a consistent date format.
"""
return date_str.isnumeric() and date_str.startswith('20') and len(date_str) == 8
def check_expiration_date(folder: Path):
expiration_date = datetime.now(timezone.utc) - timedelta(weeks=EXPIRATION_WEEKS)
folder_date = folder.name.split('-')[0]
if validate_date(folder_date):
try:
folder_date = datetime.strptime(folder_date, '%Y%m%d')
except Exception:
return False # Folder name is not a valid date
return folder_date.date() < expiration_date.date()