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

cef*_*tat 8 python macos

Mac上的Python的os.path.getctime(以及一般的Unix下)没有给出创建文件的日期,而是"最后一次更改的时间"(至少根据文档).另一方面,在Finder中,我可以看到真正的文件创建时间,因此这些信息由HFS +保存.

您对如何在Python程序中获取Mac上的文件创建时间有什么建议吗?

Mil*_*les 18

st_birthtime在调用os.stat()(或fstat/ lstat)的结果上使用该属性.

def get_creation_time(path):
    return os.stat(path).st_birthtime
Run Code Online (Sandbox Code Playgroud)

您可以使用将整数结果转换为datetime对象datetime.datetime.fromtimestamp().

出于某种原因,我认为这个答案在第一次编写时并不适用于Mac OS X,但我可能会弄错,现在它确实有效,即使使用旧版本的Python也是如此.后代的答案如下.


使用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
Run Code Online (Sandbox Code Playgroud)

使用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())
Run Code Online (Sandbox Code Playgroud)

  • 在El Capitan上,你可能想使用`libc = CDLL('/ usr/lib/libc.dylib')`而不是`libc = CDLL('libc.dylib')`如果你得到一个`OSError:dlopen(libc) .dylib,6):找不到图像. (2认同)