Python从FTP服务器下载文件,如果文件已添加到FTP服务器在最近N小时前?



如果文件已添加到最近12小时前,请帮助从FTP服务器下载文件,目前我能够从FTP服务器下载最新文件,但不确定如何添加逻辑为最近12小时前,如果文件已添加到FTP服务器

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:Filesrestaurant \" + latest_name, 'wb') as f:
ftp.retrbinary('RETR '+ latest_name, f.write)
print("filehasbeendownload")

计算时间阈值。解析MDTM返回的时间。和比较:

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

如果你的服务器支持MLSD命令,你最好使用它,而不是低效地为每个文件调用MDTM:
下载仅昨天's文件在Python

也可以使用LIST。要了解获取文件时间戳的方法,请参见:
如何获取FTP文件's使用Python ftplib修改时间

最新更新