【问题标题】:unable to extract correct timestamp of a directory无法提取目录的正确时间戳
【发布时间】:2016-08-21 06:03:38
【问题描述】:

我正在尝试获取在特定时间创建的特定文件夹中的目录列表(例如,在第 11 小时创建的所有文件)。以下是我的代码:

import time
import os
def get_information(directory):
    file_dict={}
    for i in os.listdir(directory):
        a=os.stat(os.path.join(directory,i))
        b=time.gmtime(a.st_ctime)
        newTime=b.tm_hour
        if(file_dict.has_key(newTime)):
            file_dict[newTime].append(i)
        else:
            file_dict[newTime]=[]
            file_dict[newTime].append(i)
    return file_dict

虽然我可以看到在第 11 小时内创建了文件,但上面的代码无法提取它。

drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181071677
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181071621
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181071661
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181071625
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181071673
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181055504
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181055500
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181055508
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181055512
drwxrwxr-x   2 oamops   oamgroup     512 Aug 21 11:23 69-2181055516

还有一点需要注意的是,从第 0 小时到第 5 小时有数据,然后从第 18 小时开始数据。

【问题讨论】:

    标签: python-2.7 datetime time


    【解决方案1】:

    尝试创建一个过滤函数:

    import os, datetime
    
    def check_time(path):
       t = datetime.datetime.fromtimestamp(os.path.getmtime(path))
       return t.hour == 11
    

    然后只需过滤您的目录:

    filtered = filter(check_time, os.listdir(r'my/path'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2020-03-26
      相关资源
      最近更新 更多