python脚本获取文件的创建于修改日期并计算时间差

时间:2021-08-27 02:20:51

由于在计算一个算法的运行时间的时候,需要将文件的创建日期与修改日期读取到,然后计算两者之差,在网上搜索了相关的程序之后,自己又修改了一下,把代码贴在这里,供以后查阅使用,也希望可以帮到其他人。

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Mon Dec 12 14:59:46 2016
 4 
 5 @author: shenruixue
 6 
 7 to calculate size after filter in conv and pool
 8 """
 9 import os.path, time
10 import exceptions
11 class TypeError (Exception):
12   pass
13 if __name__ == '__main__':
14  file_srx = open("train_1920_1080.set")#其中包含所有待计算的文件名
15  line = file_srx.readline()
16  diff_time_all = 0
17  while line:
18   f = line[:-1]    # 除去末尾的换行符
19   print (f)
20   print ('***********************************************************')
21   mtime = time.ctime(os.path.getmtime(f))
22   ctime = time.ctime(os.path.getctime(f))
23   mtime_s = (os.path.getmtime(f))
24   ctime_s = (os.path.getctime(f))
25   print "Last modified : %s, last created time: %s" % (mtime, ctime)
26   diff_time = (int(mtime_s) - int(ctime_s))
27   diff_time_all = diff_time_all + diff_time
28   print "diff time is ", diff_time
29   line = file_srx.readline() 
30  print "diff_time_all is ", diff_time_all
31  file_object = open('train_1920_1080.txt', 'w')
32  file_object.write(str(diff_time_all))
33  file_object.close( )