Python 转换日期时间以在 os.utime 中使用

标签 python datetime ftp ftplib

我无法在 Python 中为我的文件设置 ctime/mtime。首先,我通过 FTP 获取文件的原始时间戳。

我唯一想要的是使用 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

             

我想将原始时间戳设置为下载的文件

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 的可用元组

最佳答案

来自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.

你没有给它一个元组。在这种情况下,只需将 atimemtime 设置为相同的值即可:

os.utime(fileName, (orgTime, orgTime))

fileName 是一个字符串,所以 fileName.close() 将不起作用(您会得到一个属性错误),只需删除该行即可。

orgTime 必须是整数;你给它一个时间元组;使用 time.mktime() 将其转换为以秒为单位的时间戳:

settime = time.mktime(ftime.timetuple())

关于Python 转换日期时间以在 os.utime 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182623/

相关文章:

python - 为什么在函数内部调用时 exec() 的工作方式不同以及如何避免它

c# - 是否有可以处理从现在到公元前 12,000 年的日期的 C# 日期时间库?

sql - 计算两个日期之间的营业时间

c# - 此值是否为有效年份 C#

python - 在 tensorflow 中使用动态形状调整图像大小

python - 使用 pip3 : module "importlib._bootstrap" has no attribute "SourceFileLoader"

python - 从多维 numpy 数组中选择随机数组并进行替换

Java 和 FTP 编辑在线文本文件

c# - 从 WebRequestMethods.Ftp.ListDirectoryDe​​tails 中提取文件名

php - 将 2700 多个文件名与数据库表中的 29000 多行进行比较