【问题标题】:Comparing files using timestamp in Python在 Python 中使用时间戳比较文件
【发布时间】:2020-05-04 17:58:43
【问题描述】:

我正在尝试将我的文件与时间戳进行比较。
例如,有一个包含文件的目录,例如
a.xls, a.log, a.txt
b.xls, b.log, b.txt
c.xls, c.log, c.txt
在这里我必须找到a.log和a.txt的时间戳(日期时间)是否大于a.xls的时间戳
我研究了如何获取文件的时间戳,比较两个文件的时间戳。
我不知道我的方向是否正确。
请指导我如何看待这个问题并给出一些合乎逻辑的指导。

【问题讨论】:

标签: python timestamp file-comparison


【解决方案1】:

在 Python 中,如果您能够创建日期时间对象,那么您可以使用比较运算符来比较它们。

因此,要获取文件的日期时间对象,您可以这样做:

modTimesinceEpoc = os.path.getmtime(filePath)
 # Convert seconds since epoch to readable timestamp
modificationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))

然后你可以直接使用时间戳并进行比较,得到你想要的输出。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我已经设法为上述问题编写了代码。

    import os
    path = 'D:/Newfolder/A'
    xls_file = []
    for i in os.listdir(path):
        if i.endswith('xls'):   
            file_name = (i.split('.')[0])  
            ext_name = (i.split('.')[1])   
            xls_file.append(file_name)   
    for fname in os.listdir(path):  
        for i in xls_file: 
            if fname.__contains__(i) and not fname.endswith('xls'):
                log_txt = os.path.getmtime(path+'/'+fname)   
                xls_tym = os.path.getmtime(path+'/'+i+'.xls')  
                if xls_tym < log_txt:
                    pass
                else:
                    print(i+'.xls')
    

    它可能不是干净的代码,但我认为代码工作正常
    请建议是否必须进行任何更改

    【讨论】:

    • 一个建议,看看pathlibglob 处理路径和文件名。此外,避免直接使用像 fname.__contains__(i) 这样的 dunderscore 方法 - 还有更多可读的替代方法,例如i in fname.
    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2012-07-09
    • 2013-01-12
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多