在Mac(以及通用的Unix系统)上,Python的os.path.getctime函数无法提供文件创建时间,而只能提供“最后更改时间”(至少按照文档所述)。但是,在Finder中,我可以看到实际的文件创建时间,因此HFS+将此信息保存。
你有什么建议可以在Python程序中获取Mac上的文件创建时间吗?
在Mac(以及通用的Unix系统)上,Python的os.path.getctime函数无法提供文件创建时间,而只能提供“最后更改时间”(至少按照文档所述)。但是,在Finder中,我可以看到实际的文件创建时间,因此HFS+将此信息保存。
你有什么建议可以在Python程序中获取Mac上的文件创建时间吗?
在调用 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())
OSError: dlopen(libc.dylib, 6): image not found
错误,你可能需要使用libc = CDLL('/usr/lib/libc.dylib')
而不是libc = CDLL('libc.dylib')
。 - Thomas Orozco平台上的ctime不同:在一些系统(如Unix)中,它是最后元数据更改的时间,在另一些系统(如Windows)中,它是创建时间。这是因为Unix通常不保留“原始”创建时间。
尽管如此,您仍然可以通过stat模块访问操作系统提供的所有信息。
stat模块定义了常量和函数,用于解释os.stat()、os.fstat()和os.lstat() (如果存在)的结果。有关stat、fstat和lstat调用的完整详细信息,请参阅您系统的文档。
stat.ST_CTIME
由操作系统报告的“ctime”。在一些系统(如Unix)中,它是最后元数据更改的时间,在另一些系统(如Windows)中,它是创建时间(有关详细信息,请参阅平台文档)。
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
要快1000倍以上,因为它会创建临时文件,然后一次性执行所有文件的stat
调用。