Use datetime module
>>> from datetime import datetime, timedelta
>>> fm = "%d-%b-%y"
>>> delta = timedelta(days=14)
>>> d = datetime.strptime("28-FEB-12", fm)
>>> (d - delta).strftime(fm)
'14-Feb-12'
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 760
Skill Endorsements: 11
This should give you some hints ...
# use Python module datetime
# to check if a dated filename +14 days is older than todays date
import datetime as dt
# dated filename for test
file_str = "28-Feb-12"
# abbreviated month list
month_abv = ['Jan','Feb','Mar','Apr',
'May','Jun','Jul','Aug',
'Sep','Oct','Nov','Dec']
# convert to a string module datetime can handle
# eg. "28-Feb-12" converts to "2012-02-28"
raw_date = file_str.split('-')
print(raw_date) # test
'''output >>>
['28', 'Feb', '12']
'''
day = int(raw_date[0])
month = month_abv.index(raw_date[1]) + 1
year = int(raw_date[2]) + 2000
file_date = dt.date(year, month, day)
print(file_date, type(file_date)) # test
'''output >>>
(datetime.date(2012, 2, 28), <type 'datetime.date'>)
'''
# add 14 days to a given date
delta = dt.timedelta(days=14)
add14 = file_date + delta
print(add14, type(add14)) # test
'''output >>>
(datetime.date(2012, 3, 13), <type 'datetime.date'>)
'''
# is add14 older than todays date?
today = dt.date.today()
if add14 < today:
print("%s is older than %s" %(add14, today))
'''possible output >>>
2012-03-13 is older than 2012-06-01
'''
# optionally
# convert datetime type back to file name string
# eg. "2012-03-13" converts to "13-Mar-12"
date14 = add14.strftime("%d-%b-%y")
print(date14, type(date14))
'''output >>>
('13-Mar-12', <type 'str'>)
'''
You can simplify your code using the hints Gribouillis gave you.
vegaseat
DaniWeb's Hypocrite
6,464 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,607
Skill Endorsements: 34
You must not compare strings but datetime instances
now_date = datetime.now()
dir_date = datetime.strptime(fname, fm)
del_date = now_date - timedelta(days = 14)
if dir_date <= del_date :
print "Folder %s is older than 14 days" % fname
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 760
Skill Endorsements: 11
Question Answered as of 11 Months Ago by
Gribouillis
and
vegaseat