Python 使用“保留修改的时间戳”压缩文件

Python 使用“保留修改的时间戳”压缩文件,python,gzip,Python,Gzip,我一直在设置文件时间戳,同样根据python,语法不像gzip.GzipFile(filename=outputfile,mode='wb',compresslevel=9,mtime=ftime),但是当我使用gzip.GzipFile(outputfile,'wb',9,mtime=ftime)时,它在工作,但时间戳除外 def compresse_file(file,ftime): data = open(file,'rb') outputfile = fi

我一直在设置文件时间戳,同样根据python,语法不像
gzip.GzipFile(filename=outputfile,mode='wb',compresslevel=9,mtime=ftime)
,但是当我使用
gzip.GzipFile(outputfile,'wb',9,mtime=ftime)
时,它在工作,但时间戳除外

def compresse_file(file,ftime):
        data = open(file,'rb')
        outputfile = file +".gz"
        gzip_file = gzip.GzipFile(outputfile,'wb',9,mtime=ftime)
        gzip_file.write(data.read())
        gzip_file.flush()
        gzip_file.close()
        data.close()
        os.unlink(file)
以下是输出:

root@ubuntu:~/PythonPractice-# python compresses_file.py
Size      Date      File Name
5 MB      30/12/13  test.sh
Compressing...
test.sh 1388403823.0
file status after compressesion
5 kB      31/12/13  test.sh.gz
root@ubuntu:~/PythonPractice-# date -d @1388403823.0
Mon Dec 30 17:13:43 IST 2013
正如您在中所看到的,
mtime
参数是写入流的时间戳,它不影响创建的gzip文件的时间戳。这是使用
gunzip-N
解压缩后的文件将具有的时间戳

例如:

>>> import datetime
>>> import gzip
>>> ts = datetime.datetime(2010, 11, 12, 13, 14).timestamp()
>>> zf = gzip.GzipFile('test.gz', mode='wb', mtime=ts)
>>> zf.write(b'test')
>>> zf.flush()
>>> zf.close()
并解压缩:

$gunzip-N test.gz
$stat-c%y测试
2010-11-12 13:14:00.000000000 +0100
如果希望创建的gzip文件具有特定的时间戳,请使用来更改它:

...
st = os.stat(file)
...
os.utime(outputfile, (st.st_atime, st.st_mtime))
...

你真的是以
root
的身份这么做的@是的。。这是一台试验机PGNU
gzip
命令保留与源文件相同的时间戳,这就是我要寻找的,但仍然是同一个问题,您的解决方案也不起作用它对我来说很好。你能更详细地描述一下结果如何偏离你的预期吗?什么时间戳改变了什么?谢谢,最后我使用了
utime
,但仍然
gzip
不在这里工作就是完整的代码