Search code examples
pythondatetimeftpftplib

Python converting datetime to be used in os.utime


I cannot set ctime/mtime on my file within Python. First I get the original timestamp of the file through FTP.

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

Then I download the file

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

    

This is how I am trying to do it

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)

                 
    

The error is :

    os.utime(fileName, orgTime)
TypeError: utime() arg 2 must be a tuple (atime, mtime)

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


Solution

  • From the os.utime() documentation:

    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.

    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 is a string, so fileName.close() won't work (you'll get an attribute error), just drop that line.

    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())