0

I'm trying to delete files from a folder where the date modified is greater than 3 days.

    numdays = 86400 * 3  # Seconds in a day times 3 days
from datetime import datetime
a = datetime.now()
for delete_f in os.listdir(src1):
    file_path = os.path.join(src1, delete_f)
    try:
        if (a - datetime.fromtimestamp(os.path.getmtime(file_path)) >   numdays):

      os.unlink(file_path)
except Exception as e:
    print (e)

I get the error unorderable types: datetime.timedelta() > int()

I'm not really sure how to go about getting the numdays part, anyone have suggestions? TIA

2 Answers2

4

You want to make numdays a timedelta object.

numdays = datetime.timedelta(days=3)

So you are now comparing two datetime objects.

Programmer
  • 293
  • 4
  • 15
1

Don't use datetime.now() -- it returns the current local time as a naive datetime object that may be ambiguous. Use time.time() instead:

#!/usr/bin/env python
import os
import time

cutoff = time.time() - 3 * 86400 # 3 days ago
for filename in os.listdir(some_dir):
    path = os.path.join(some_dir, filename)
    try:
        if os.path.getmtime(path) < cutoff: # too old
            os.unlink(path) # delete file
    except EnvironmentError as e:
        print(e)

See more details on why you should not use datetime.now() in Find if 24 hrs have passed between datetimes - Python


Unrelated: here's pathlib-based solution:

#!/usr/bin/env python3
import time
from pathlib import Path

cutoff = time.time() - 3 * 86400 # 3 days ago
for path in Path(some_dir).iterdir():
    try:
        if path.lstat().st_mtime < cutoff: #NOTE: don't follow symlinks
            path.unlink() # delete old files or links
    except OSError as e:
        print(e)
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670