python - 在 Python 中使用 FTP 仅下载昨天的文件
问题描述
我只想用下面的 Python 编程代码通过 FTP 下载昨天的文件,下面的代码下载所有文件。我想根据昨天的日期检查代码中的最后修改时间戳,并仅自动下载昨天的文件。我真的需要帮助并感谢任何建议:
import ftplib
import os
from datetime import date
from dateutil import parser
FTP_HOST = "Remote IP"
FTP_USER = "Username"
FTP_PASS = "Password"
# some utility functions that we gonna need
def get_size_format(n, suffix="B"):
# converts bytes to scaled format (e.g KB, MB, etc.)
for unit in ["", "K", "M", "G", "T", "P"]:
if n < 1024:
return f"{n:.2f}{unit}{suffix}"
n /= 1024
def get_datetime_format(date_time):
# convert to datetime object
date_time = datetime.strptime(date_time, "%Y%m%d%H%M%S")
# convert to human readable date time string
return date_time.strftime("%Y/%m/%d %H:%M:%S")
# initialize FTP session
ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)
# force UTF-8 encoding
ftp.encoding = "utf-8"
# print the welcome message
print(ftp.getwelcome())
# change the current working directory to 'pub' folder and 'maps' subfolder
ftp.cwd("RemoteDirectory")
print("*"*50, "NLST", "*"*50)
print("{:20} {:19}".format("File_Name", "last_modified"))
for file_data in ftp.mlsd():
file_name,meta = file_data
# convert it to human readable format (i.e in 'KB', 'MB', etc)
last_modified = get_datetime_format(meta.get("modify"))
try:
ftp.cwd(file_name)
except Exception as e:
ftp.voidcmd("TYPE I")
last_modified = get_datetime_format(meta.get("modify"))
print(f"{file_name:20} {last_modified:19}")
ftp.retrbinary("RETR " + file_name, open(file_name, 'wb').write)
# quit and close the connection
ftp.quit()
解决方案
基于Python Datetime: All Items From Yesterday,应该这样做:
yesterday = date.today() - timedelta(days=1)
for file_data in ftp.mlsd():
file_name,meta = file_data
last_modified = datetime.strptime(meta.get("modify"), "%Y%m%d%H%M%S")
if last_modified.date() == yesterday:
ftp.retrbinary("RETR " + file_name, open(file_name, 'wb').write)
推荐阅读
- angular - makeTransliterable 不适用于自定义 ID
- javascript - 如何将多个文件发送到 fire base 存储并将其 URL 保存在实时数据库中的一条记录中
- django - pycharm django 调试配置无法识别应用程序文件夹
- java - Azure Blob 存储 Java SDK:为什么异步不起作用?
- sql-server-2012 - 更新 SQL Select 语句中每一行的变量
- php - 为什么搜索功能不能与 Select 功能一起使用?使用 PHP、jQuery、Ajax
- python - python到SQL加载csv文件给出错误“必须声明标量变量”
- react-native - 找不到 app:///index.android.bundle 的源代码
- python - 如何用pytorch做类似于numpy的trapz函数的数值积分?
- javascript - appendChild 未在 js 文件中读取