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

Python converting datetime to be used in os.utime(Python 转换日期时间以在 os.utime 中使用)
本文介绍了Python 转换日期时间以在 os.utime 中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我无法在 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.

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

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

这篇关于Python 转换日期时间以在 os.utime 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)