1、获取文件的创建、修改、访问时间
参考链接: https://www.cnblogs.com/likeatree/p/4280388.html
# -*- encoding=utf-8 -*-
import os
import time
def get_file_time(filename):
filename = os.path.abspath(filename)
create_time = os.path.getctime(filename) # 创建时间
print('old create time:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(create_time))))
update_time = os.path.getmtime(filename) # 修改时间
print('old update time:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(update_time))))
access_time = os.path.getatime(filename) # 访问时间
print('old access time:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(access_time))))
return create_time, update_time, access_time
if __name__ == '__main__':
get_file_time('E:/a.txt')
2、更改文件的修改、访问时间(创建时间没查到怎么修改,暂时不记录)
#-*- encoding=utf-8 -*-
importosimporttime
defset_file_time(filename, updatetime, access_time):#先传修改时间,再传访问时间
filename =os.path.abspath(filename)
new_updatetime= time.mktime(time.strptime(updatetime, '%Y-%m-%d %H:%M:%S'))
new_access_time= time.mktime(time.strptime(access_time, '%Y-%m-%d %H:%M:%S'))
os.utime(filename, (new_access_time, new_updatetime))if __name__ == '__main__':
set_file_time('E:/a.txt', '2018-01-08 10:50:20', '2019-07-15 04:03:01')
3、放在同一个py方便直接复制使用
#-*- encoding=utf-8 -*-
importosimporttimedefget_file_time(filename):
filename=os.path.abspath(filename)#创建时间
create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(filename)))#修改时间
update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(filename)))#访问时间
access_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getatime(filename)))returncreate_time, update_time, access_timedefset_file_time(filename, updatetime, access_time):#先传修改时间,再传访问时间
filename =os.path.abspath(filename)
new_update_time= time.mktime(time.strptime(updatetime, '%Y-%m-%d %H:%M:%S'))
new_access_time= time.mktime(time.strptime(access_time, '%Y-%m-%d %H:%M:%S'))
os.utime(filename, (new_access_time, new_update_time))defdebug():
create_time, update_time, access_time= get_file_time('E:/a.txt')
set_file_time('E:/a.txt', update_time, access_time)
get_file_time('E:/a.txt')if __name__ == '__main__':
debug()
View Code