【问题标题】:Downloading file based on last modified date fails if older than 1 day如果超过 1 天,根据上次修改日期下载文件失败
【发布时间】:2017-01-12 04:04:30
【问题描述】:

下面是一个代码 sn-p,它根据服务器和本地之间的最后修改日期下载文件。

try:
    url = "https://10.10.10.10/version.ini"
    local_ini = ".//config/version.ini"
    filetime = (time.strftime('%a, %d %b %Y %X GMT', time.gmtime(os.path.getmtime(local_ini))))
    print("File Last Modified: {0}".format(filetime))
    r = requests.get(url,stream=True)
    meta = r.headers['last-modified']
    logging.info("Web  Last Modified: {0}".format(meta))
    if filetime < meta:
        print("Newer file found! Downloading...")
        if r != False:
            try:
                fileName = os.path.basename(urlparse.urlsplit(r.url)[2])
                with open(".//config/version.ini"e, 'wb') as f:
                     shutil.copyfileobj(r.raw,f)    
            finally:
                r.close()
    else:
        logging.info('No new version found. You got the latest file!') 

except requests.exceptions.RequestException as e:  
    logging.info(e)    

当我在同一天修改文件时,我得到了正确的结果:

File Last Modified: Thu, 12 Jan 2017 03:42:23 GMT
Web  Last Modified: Thu, 12 Jan 2017 03:44:22 GMT
Newer file found! Downloading...

但是当我修改一个文件时,一天后我得到了错误的结果:

File Last Modified: Wed, 11 Jan 2017 08:38:38 GMT
Web  Last Modified: Thu, 12 Jan 2017 02:44:45 GMT
No new version found. You got the latest file!

为什么时间戳比较会给出错误的结果?

【问题讨论】:

    标签: python datetime time python-requests


    【解决方案1】:

    在您的示例中,meta 是一个字符串,而不是 time 对象。如果你比较两个datetime 对象,你会得到更好的运气:

    if (dt.datetime.strptime(filetime, '%a, %d %b %Y %X GMT') < 
            dt.datetime.strptime(meta, '%a, %d %b %Y %X GMT')):
    

    你需要:

     import datetime as dt
    

    【讨论】:

    • 我收到 TypeError: argument must be 9-item sequence, not str
    • 我误读了您的代码,我编辑了示例以使用日期时间对象。
    猜你喜欢
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2020-07-21
    • 2022-07-14
    • 2010-12-10
    相关资源
    最近更新 更多