简体   繁体   English

如何在 Python 中使用时间戳从 FTP 下载文件?

[英]How to download a file from FTP with timestamp in Python?

How can I download a file from FTP in Python in such a way that it records the timestamp?如何以记录时间戳的方式从 Python 中的 FTP 下载文件? I'd like to record both the time modified/lastupdated of the file based on the server time stamp, and also record the time at which the file was fetched.我想根据服务器时间戳记录文件的修改/上次更新时间,并记录获取文件的时间。 How can this be done?如何才能做到这一点? thanks谢谢

I think this is what you are looking for:我认为这就是你要找的:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM