Can you please help with download file from FTP server if file has been added into last 12 hours ago, currently I'm able to download latest file from FTP server, but not sure how to add logic for last 12 hours ago if files has been added into ftp server
import csv
from ftplib import FTP
import os
import time,glob
from datetime import datetime,timedelta
list_of_file =glob.glob(".\*csv*")
latest_file = max(list_of_file, key=os.path.getatime,default=None)
filename = os.path.basename('latest_file')
ftp = FTP(host='hostname')
ftp.login(user='username',passwd='pass')
ftp.cwd("Inbox")
names = ftp.nlst()
finale_names = [line for line in names if 'restaurant file' in line]
latest_time = None
latest_name = None
for name in finale_names:
time_1 = ftp.sendcmd("MDTM " + name)
if (latest_time is None) or (time_1 > latest_time):
latest_name = name
latest_time = time_1
print(latest_name)
if latest_name==filename:
print("No new file available in the FTP server")
else:
print(latest_name," is available for downloading...")
with open("C:\Files\restaurant \\" + latest_name, 'wb') as f:
ftp.retrbinary('RETR '+ latest_name, f.write)
print("filehasbeendownload")
Calculate the time threshold. Parse the times returned by MDTM
. And compare:
n = 4
limit = datetime.now() - timedelta(hours=n)
for name in finale_names:
resp = ftp.sendcmd("MDTM " + name)
# extract "yyyymmddhhmmss" part of the 213 response
timestr = resp[4:18]
time = datetime.strptime(timestr, "%Y%m%d%H%M%S")
if time > limit:
# Download
Though if your server supports MLSD
command, you better use that, instead of inefficiently calling MDTM
for each and every file:
Download only yesterday's file with FTP in Python
Or you can use LIST
. For understanding ways of retrieving file timestamps, see:
How to get FTP file's modify time using Python ftplib