比较文件创建日期

时间:2013-08-07 16:29:56

标签: python

我正在尝试根据创建日期归档旧文件。我的数据从12-17-2010开始,所以我将其设置为基准日期并从那里开始递增。这是我的代码

import os, time, tarfile
from datetime import datetime, date, timedelta
import datetime

path = "/home/appins/.scripts/test/"
count = 0
set_date = '2010-12-17'
date = datetime.datetime.strptime(set_date, '%Y-%m-%d')

while (count < 2):
    date += datetime.timedelta(days=1)
    tar_file = "nas_archive_"+date.strftime('%m-%d-%y')+".tgz"
    log_file = "archive_log_"+date.strftime('%m-%d-%y')
    fcount = 0
    f = open(log_file,'ab+')
    #print date.strftime('%m-%d-%y')
    for root, subFolders, files in os.walk(path):
        for file in files:
            file = os.path.join(root,file)
            file = os.path.join(path, file)
            filecreation = os.path.getctime(file)
            print datetime.fromtimestamp(filecreation)," File Creation Date"
            print date.strftime('%m-%d-%y')," Base Date"
            if filecreation == date:
                tar.add(file)
                f.write(file + '\n')
                print file," is of matching date"
                fcount = fcount + 1
    f.close()
    count += 1

filecreation变量正在获取浮点值。如何使用它与我的基准日期进行比较?

1 个答案:

答案 0 :(得分:1)

timestamp = datetime.mktime(date.timetuple())

'timestamp'将包含与getctime返回的值相当的时间戳。关于问题下的评论:在Windows上getctime返回创建时间,在UNIX修改时间(http://docs.python.org/3.1/library/os.path.html)。

编辑(关于评论中的问题):

1)mktime出现在Python 2.x中:http://docs.python.org/2/library/time.html#time.mktime

2)Get file creation time with Python on linux

EDIT2:

显然这是愚蠢的,应该按照下面的tdelaney的建议进行:

date.fromtimestamp(filecreation)

并比较日期,而不是时间戳。我没看到算法实际上在做什么:)