在调用os.stat()(或fstat/lstat)的结果上使用st_birthtime属性。
def get_creation_time(path):
return os.stat(path).st_birthtime
您可以使用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
使用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())