下面是一段代码片段,它根据服务器和本地之间的上次修改日期下载文件。
$ rvm osx-ssl-certs status all
Certificates for /etc/openssl/cert.pem: Up to date.
Certificates for /usr/local/etc/openssl/cert.pem: Up to date.
[~/couponler2 (production)]
$ rvm osx-ssl-certs update all
Updating certificates for /etc/openssl/cert.pem: Already up to date.
Updating certificates for /usr/local/etc/openssl/cert.pem: Already up to date.
当我在同一天修改文件时,我得到了正确的结果:
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...
为什么时间戳比较会给出错误的结果?
答案 0 :(得分:0)
在您的示例中,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