Mac上(以及一般Unix下)的Python os.path.getctime不会给出文件创建的日期,而是“最后一次更改的时间”(根据文档至少)。另一方面,在Finder中,我可以看到真正的文件创建时间,因此这些信息由HFS +保存。在Mac上使用Python获取文件创建时间
对于如何在Python程序中获取Mac上的文件创建时间,您有什么建议吗?
Mac上(以及一般Unix下)的Python os.path.getctime不会给出文件创建的日期,而是“最后一次更改的时间”(根据文档至少)。另一方面,在Finder中,我可以看到真正的文件创建时间,因此这些信息由HFS +保存。在Mac上使用Python获取文件创建时间
对于如何在Python程序中获取Mac上的文件创建时间,您有什么建议吗?
使用st_birthtime
财产上os.stat()
(或fstat
/lstat
)呼叫的结果。
def get_creation_time(path):
return os.stat(path).st_birthtime
您可以使用datetime.datetime.fromtimestamp()
将整数结果转换为日期时间对象。
出于某种原因,我不认为这在第一次写这个答案时适用于Mac OS X,但我可能会误解,现在它甚至可以使用旧版本的Python。旧的答案在后面。
使用访问系统调用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())
ctime在平台上有所不同:某些系统(如Unix)是最后一次元数据更改的时间,在其他系统(如Windows)上,创建时间为。这是因为Unices通常不会保留“原创”创作时间。
这就是说你可以访问操作系统提供的所有信息,stat模块。
The stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). For complete details about the stat, fstat and lstat calls, consult the documentation for your system.
stat.ST_CTIME
The “ctime” as reported by the operating system. On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details).
重复:HTTP:/ /stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python – 2009-06-03 21:20:36
@ S.Lott :并非如此,因为在Mac上获取文件创建时间本质上是非跨平台的。 – Miles 2009-06-03 21:25:56
@Miles:也许这是真的,但那里的答案完全适用于这个问题。 – 2009-06-03 21:29:28