我需要下载SFTP中的所有文件,并且修改日期为昨天。这是我最近的尝试。我确信它与时间戳有关,但是所有试图从两个变量中剥离时间戳的尝试都无法解决我的问题。下面的代码下载了14个文件中的11个,其修改日期为昨天的时间戳,介于12:29:05 AM和2:28:46 AM之间。这3个丢失的文件的时间戳为11:35:25至11:29:34。我正在使用SQL Server代理安排运行时间,并且服务器以与我硬编码到脚本中的服务帐户相同的方式运行脚本。
from os.path import basename
import os.path
import paramiko
import datetime
from datetime import date, timedelta
#Assigning variables to upload file to SFTP
host = 'SERVER'
port = PORT
transport = paramiko.Transport((host, port))
##setting up transport
username = 'UNAME'
password = 'PW'
##connecting to FTP
transport.connect(hostkey = None, username = username, password = password,pkey = None)
sftp = paramiko.SFTPClient.from_transport(transport)
##create yesterday var and normalize it
yesterday = date.today() - timedelta(days=1)
yDay = yesterday.day
yYear = yesterday.year
yMonth = yesterday.month
##create a list of all files and get name/modified date of the fiels.
for file in sftp.listdir_attr('WORKING DIRECTORY'):
i = file.st_mtime
filedate = date.isoformat(i)
fdDay = filedate.day
fdYear = filedate.year
fdMonth = filedate.month
if fdDay == yDay and fdYear == yYear and fdMonth == yMonth:
remotepath = 'WORKING DIRECTORY' + file.filename
localpath = 'LOCAL PATH' + file.filename
sftp.get(remotepath, localpath)
#Close Connection
sftp.close()
transport.close()
首先计算昨天开始和结束的时间戳:
from datetime import datetime, time, timedelta
today_midnight = datetime.combine(datetime.today(), time.min)
yesterday_midnight = today_midnight - timedelta(days=1)
(基于What was midnight yesterday as an epoch time?)
然后将这些时间戳与文件的时间戳进行比较:
for file in sftp.listdir_attr('/remote/path'):
mtime = datetime.fromtimestamp(file.st_mtime)
if (yesterday_midnight <= mtime) and (mtime < today_midnight):
print(file.filename)