如何在Python中使用带时间戳的ftp下载文件?

时间:2013-07-13 21:56:32

标签: python url web ftp

如何以Python记录时间戳的方式从FTP下载FTP文件?我想基于服务器时间戳记录文件的修改/最后更新时间,并记录文件的提取时间。如何才能做到这一点?感谢

1 个答案:

答案 0 :(得分:3)

我认为这就是你要找的东西:

import os
import ftplib
import datetime

local = 'LOCATION/WHERE/YOU/WANT/TO/DOWNLOAD'
time_stamps = {}

with ftplib.FTP('ftp.your.host') as server:
    server.login(user='username', passwd='password')
    for name, params in server.mlsd():
        if name != '.' and name != '..':
            with open(os.path.join(local, name), 'w+b') as download:
                try:
                    server.retrbinary('RETR ' + name, download.write)
                    dt = params['modify']
                    time_stamps[name] = {
                        'modified': '{yy}-{mo}-{dd} {hh}:{mm}:{ss}.{ms}'.format(
                            yy = dt[:4],
                            mo = dt[4:6],
                            dd = dt[6:8],
                            hh = dt[8:10],
                            mm = dt[10:12],
                            ss = dt[12:14],
                            ms = dt[14:]
                        ),
                        'fetched': str(datetime.datetime.now())
                    }
                except ftplib.error_perm:
                    pass

print(time_stamps)