修改文件时间属性的方法

Windows下:

1. bat文件?

2. Python

import os,sys,time
from stat import *
filename='ChenRef.bib'
#指定期望修改后的时间
TimeForChange = '2017-01-10 07:51:21'
#转换时间格式为long型
ConverTime = time.mktime(time.strptime( TimeForChange,'%Y-%m-%d %H:%M:%S') )
#print(TimeForChange+' 转换后:'+str(ConverTime))

print('-------------修改前----------------')
##创建时间
print('创建时间  '+time.ctime(os.path.getctime(filename)))
##最后修改时间
print('修改时间  '+time.ctime(os.path.getmtime(filename)))
##访问时间
print('访问时间  '+time.ctime(os.path.getatime(filename)))

#修改文件时间戳
times=(ConverTime,ConverTime)
#进行修改
os.utime(filename, times)

print'-------------修改后----------------')
#创建时间
print('创建时间  '+time.ctime(os.path.getctime(filename)))
#最后修改时间
print('修改时间  '+time.ctime(os.path.getmtime(filename)))
#访问时间
print('访问时间  '+time.ctime(os.path.getatime(filename)))  


 

 改成函数的版本:

import os,sys,time,random
from stat import *

def changeFileTime(fname, newtime):
    ConverTime = time.mktime(time.strptime( newtime,'%Y-%m-%d %H:%M:%S'))
    times=(ConverTime,ConverTime)
    os.utime(fname, times)


# get the files in current dir
files = os.listdir()
for f in files:
    if os.path.isdir(f):
        files.remove(f)

# generate random times
filenum = len(files)
newtimes = []
for i in range(filenum):
    hour   = '{:0>2}'.format(random.randint(15,20))
    minute = '{:0>2}'.format(random.randint(0,59)) #http://blog.csdn.net/handsomekang/article/details/9183303
    second = '{:0>2}'.format(random.randint(0,59))
    newtimes.append('2015-04-26 '+hour+':'+minute+':'+second)

for (file, newtime) in zip(files, newtimes):
    changeFileTime(file, newtime)


posted @ 2015-02-08 20:01  withChengChen  阅读(2243)  评论(0编辑  收藏  举报