解决Python中比较文件创建日期的问题

59 阅读2分钟

我们需要对旧文件进行归档,归档的依据是文件的创建日期。我们的数据从2010年12月17日开始,所以我们以这个日期作为基准日期,然后以此为基础逐日递增。我们使用了Python进行该操作,代码如下:

huake_00066_.jpg

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 variable is getting float value. How can I use it to compare with my base date?

在这个代码中,filecreation变量得到的filecreation值是一个浮点数,因此无法直接与我们的基准日期进行比较。

2、解决方案

为了解决这个问题,我们可以使用datetime.mktime()函数将我们的基准日期转换为时间戳,然后将filecreation变量的值也转换为时间戳,再进行比较。

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

if filecreation == timestamp:

这样,我们就能够对文件创建日期进行准确的比较,从而实现文件的归档。

代码示例

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"

            # 将基准日期转换为时间戳
            timestamp = datetime.mktime(date.timetuple())

            # 将文件创建日期转换为时间戳
            filecreation_timestamp = datetime.mktime(datetime.fromtimestamp(filecreation).timetuple())

            if filecreation_timestamp == timestamp:
                tar.add(file)
                f.write(file + '\n')
                print file," is of matching date"
                fcount = fcount + 1
    f.close()
    count += 1

这样,我们的代码就可以正确地比较文件创建日期,从而实现文件的归档。