问题描述
我无法在 python 中对我的文件设置 ctime/mtime.首先我通过 ftp 获取文件的原始时间戳.
i cannot set ctime/mtime on my file within python. first i get the original timestamp of the file through ftp.
我唯一想要的就是使用 ftplib 在我下载的文件上保留原始时间戳.
the only thing i want is to keep the original timestamps on my downloaded files using the ftplib.
def getfiletime(ftp,name): try : modifiedtime = ftp.sendcmd('mdtm ' name) filtid = datetime.strptime(modifiedtime[4:], "%y%m%d%h%m%s").strftime("%d %b %y %h:%m:%s") return filtid except : return false
然后我下载文件
def downloadfile(ftp, filename) : try: ftp.retrbinary('retr %s' % filename,open(filename, 'wb').write) except ftplib.error_perm: print 'error: cannot read file "%s"' % filename os.unlink(filename) return false else: print '*** downloaded "%s" to cwd' % filename return true
我想为下载的文件设置原始时间戳
and the i want to set the original timestamp to the downloaded file
def modifytimestaptooriginal(filename, orgtime): #try: os.utime(filename, orgtime) filename.close() # return true # except: # return false
这就是我尝试的方式
ftp, files = f.loginftp(host,user,passwd,remotedir) for i in files : if not f.isdir(ftp,i) : fixtime = datetime.strptime(varfixtime, "%d-%m-%y %h:%m:%s") ftime = f.getfiletime(ftp,i) if ftime >= fixtime : print (ftime) os.chdir('c:/testdownload') f.downloadfile(ftp,i) settime = ftime.timetuple() print "settime '%s'" % settime #f.modifytimestaptooriginal(i, settime)
错误是:
os.utime(filename, orgtime) typeerror: utime() arg 2 must be a tuple (atime, mtime)
谁能帮我给我一个更好的方法来保留原始文件时间戳或如何将 ftime 转换为 os.utime 的可用元组
can anyone help me either give me a better way to keep the original file timestamps or how to convert the ftime to a usable tuple for os.utime
推荐答案
来自 os.utime() 文档:
from the os.utime() documentation:
否则,times 必须是数字的二元组,格式为 (atime, mtime),分别用于设置访问时间和修改时间.
otherwise, times must be a 2-tuple of numbers, of the form (atime, mtime) which is used to set the access and modified times, respectively.
你没有给它一个元组.在这种情况下,只需将 atime 和 mtime 都设置为相同的值:
you are not giving it a tuple. in this case, just set both atime and mtime to the same value:
os.utime(filename, (orgtime, orgtime))
filename 是一个字符串,所以 filename.close() 不起作用(你会得到一个属性错误),只需删除该行.
filename is a string, so filename.close() won't work (you'll get an attribute error), just drop that line.
orgtime 必须是整数;你给它一个时间元组;使用 time.mktime 将其转换为以秒为单位的时间戳():
orgtime must be an integer; you are giving it a time tuple; convert it to a timestamp in seconds since the epoch with time.mktime():
settime = time.mktime(ftime.timetuple())