Reputation: 87
I have a list of folders. I iterate through each folder and read the filenames and extract the date from them which is in the format 21Mar15. Next I convert the the date to 2015-03 as string or object. I want to find out which is the latest file or rather get the latest date from each folder into a variable. I am badly stuck. Please help. My code goes like this:
folders = []
folders = ftp.nlst()
folders = map(str, folders)
folders.sort()
new_batches = [folder for folder in folders]
#gets a list of folders in the ftp
def folder_num(folder):
ftp.cwd(folder)
x=[]
x=ftp.nlst()
return x
folder_list = len(folder)
for batches in new_batches:
y=folder_num(batches)
if batches == "ABCD":
for b in y:
if (len(b)== 19):
#print b[8:15]
date = datetime.datetime.strptime(b[8:15], '%d%b%y').date().strftime('%Y-%m')
print b + " "+ date
else:
#print b[9:16]
date = datetime.datetime.strptime(b[9:16], '%d%b%y').date().strftime('%Y-%m')
print b +" " + date
ftp.cwd("//")
elif batches == "EFGH":
for b in y:
if (len(b)== 19):
#print b[8:15]
date = datetime.datetime.strptime(b[8:15], '%d%b%y').date().strftime('%Y-%m')
print b +" " + date
else:
#print b[19:26]
date = datetime.datetime.strptime(b[19:26], '%d%b%y').date().strftime('%Y-%m')
print b +" " + date
ftp.cwd("//")
The output is as follows:
ABCD
abcd23Mar15 2015-03
abcd130Apr15 2015-04
EFGH
efgc12Apr15 2015-04
efgh115Feb15 2015-02
I need to have
var1_for_ABCD = 2015-04
var2_for_EFGH = 2015-04
Or, Please help me to calculate the latest date, for each folder.
Please help. Thanks in Advance
Upvotes: 1
Views: 366
Reputation: 104712
Both the datetime
objects you're creating temporarily, and the YYYY-MM
strings you're building from them are comparable with <
. You can find the maximum simply by comparing each date with the maximum that you've seen so far:
max_date = ""
for b in y:
if (len(b)== 19):
date = datetime.datetime.strptime(b[8:15], '%d%b%y').date().strftime('%Y-%m')
if data > max_date:
max_date = date
else:
#print b[9:16]
date = datetime.datetime.strptime(b[9:16], '%d%b%y').date().strftime('%Y-%m')
if data > max_date:
max_date = date
# do something here with max_date?
Upvotes: 2