Reputation: 41
I need to remove files that are older than 14 days from a directory that stores our backups. I can get the time of an individual file by using something like this:
start = (os.path.getmtime(join(dirpath, name))/3600*24)
But I'm getting confused with how I use timedelta to find the difference between this and the current date.
I'd like to use something like this:
d = (datetime.timedelta(time.now() - os.path.getmtime(join(dirpath, dirname))
but I'm just not getting it. I'm on my own here, and I'd love some help.
Upvotes: 4
Views: 1378
Reputation: 45542
aix has a perfectly good answer using the time
module. Here's an answer that uses datetime
.
from datetime import *
maxdays = timedelta(14)
mtime =datetime.fromtimestamp(os.path.getmtime(filename))
if mtime - datetime.now() > maxdays:
print filename, 'older than 14 days'
Upvotes: 0
Reputation: 74645
a timedelta
is the result of subtracting a datetime
from another datetime
. in this example i show that my /bin/bash
is 1168 days and some older than my /dev/null
:
>>> import datetime
>>> import os.path
>>> datetime.datetime.fromtimestamp(os.path.getmtime("/dev/null"))
datetime.datetime(2011, 7, 24, 18, 58, 28, 504962)
>>> datetime.datetime.fromtimestamp(os.path.getmtime("/bin/bash"))
datetime.datetime(2008, 5, 12, 15, 2, 42)
>>> datetime.datetime.fromtimestamp(os.path.getmtime("/dev/null"))-datetime.datetime.fromtimestamp(os.path.getmtime("/bin/bash"))
datetime.timedelta(1168, 14146, 504962)
>>> d = datetime.datetime.fromtimestamp(os.path.getmtime("/dev/null"))-datetime.datetime.fromtimestamp(os.path.getmtime("/bin/bash"))
>>> d.days
1168
Upvotes: 2
Reputation: 3107
datetime.datetime.now()-datetime.timedelta(days=14)
Something like that?
Upvotes: 0
Reputation: 500357
Try:
if time.time() - os.path.getmtime(filename) > 14 * 24 * 3600:
print 'the file is older than 14 days'
Upvotes: 5