代码之家  ›  专栏  ›  技术社区  ›  cefstat

在Mac上使用Python获取文件创建时间

  •  12
  • cefstat  · 技术社区  · 16 年前

    Mac上的Python os.path.getctime(通常在Unix下)不会给出文件创建的日期,而是“上次更改的时间”(至少根据文档)。另一方面,在Finder中,我可以看到实际的文件创建时间,因此这些信息由HFS+保存。

    3 回复  |  直到 16 年前
        1
  •  21
  •   Miles    10 年前

    使用 st_birthtime 根据致电结果确定财产 os.stat() fstat / lstat ).

    def get_creation_time(path):
        return os.stat(path).st_birthtime
    

    datetime.datetime.fromtimestamp() .


    ctypes stat64 (适用于Python 2.5+):

    from ctypes import *
    
    class struct_timespec(Structure):
        _fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]
    
    class struct_stat64(Structure):
        _fields_ = [
            ('st_dev', c_int32),
            ('st_mode', c_uint16),
            ('st_nlink', c_uint16),
            ('st_ino', c_uint64),
            ('st_uid', c_uint32),
            ('st_gid', c_uint32), 
            ('st_rdev', c_int32),
            ('st_atimespec', struct_timespec),
            ('st_mtimespec', struct_timespec),
            ('st_ctimespec', struct_timespec),
            ('st_birthtimespec', struct_timespec),
            ('dont_care', c_uint64 * 8)
        ]
    
    libc = CDLL('libc.dylib') # or /usr/lib/libc.dylib
    stat64 = libc.stat64
    stat64.argtypes = [c_char_p, POINTER(struct_stat64)]
    
    def get_creation_time(path):
        buf = struct_stat64()
        rv = stat64(path, pointer(buf))
        if rv != 0:
            raise OSError("Couldn't stat file %r" % path)
        return buf.st_birthtimespec.tv_sec
    

    subprocess stat

    import subprocess
    
    def get_creation_time(path):
        p = subprocess.Popen(['stat', '-f%B', path],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if p.wait():
            raise OSError(p.stderr.read().rstrip())
        else:
            return int(p.stdout.read())
    
        2
  •  2
  •   Community Mohan Dere    5 年前

    ctime在平台上有所不同:

    stat


    操作系统报告的ctime。在某些系统(如Unix)上是最后一次元数据更改的时间,在其他系统(如Windows)上是创建时间(有关详细信息,请参阅平台文档)。

        3
  •  2
  •   PascalVKooten    7 年前

    crtime .

    pip install crtime
    

    sudo crtime ./
    

    1552938281  /home/pascal/crtime/.gitignore
    1552938281  /home/pascal/crtime/README.md
    1552938281  /home/pascal/crtime/crtime
    1552938281  /home/pascal/crtime/deploy.py
    1552938281  /home/pascal/crtime/setup.cfg
    1552938281  /home/pascal/crtime/setup.py
    1552938961  /home/pascal/crtime/crtime.egg-info
    1552939447  /home/pascal/crtime/.git
    1552939540  /home/pascal/crtime/build
    1552939540  /home/pascal/crtime/dist
    

    xstat 有时会提到这一点,因为这会创建一个临时文件,然后执行 stat 一次调用所有文件。