简体   繁体   English

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

[英]Get file creation time with Python on Mac

Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). 在Mac上(以及一般在Unix下),Python的os.path.getctime不会提供文件创建的日期,而是给出“最后一次更改的时间”(至少根据文档而言)。 On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+. 另一方面,在Finder中,我可以看到实际的文件创建时间,因此此信息由HFS +保留。

Do you have any suggestions on how to obtain the file creation time on the Mac in a Python program? 您对如何在Mac上的Python程序中获取文件创建时间有任何建议吗?

Use the st_birthtime property on the result of a call to os.stat() (or fstat / lstat ). 在调用os.stat() (或fstat / lstat )的结果上使用st_birthtime属性。

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

You can convert the integer result to a datetime object using datetime.datetime.fromtimestamp() . 您可以使用datetime.datetime.fromtimestamp()将整数结果转换为datetime对象。

For some reason I don't think this worked on Mac OS X when this answer was first written, but I could be mistaken, and it does work now, even with older versions of Python. 出于某种原因,当我第一次编写此答案时,我认为这不适用于Mac OS X,但我可能会误会,即使是使用旧版本的Python,它现在也可以正常工作。 The old answer is below for posterity. 以下是后代的旧答案。


Using ctypes to access the system call stat64 (works with Python 2.5+): 使用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

Using subprocess to call the stat utility: 使用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 differs on the platform: On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time . ctime在平台上有所不同: 在某些系统(例如Unix)上,是最后一次元数据更改的时间,而在其他系统(例如Windows)上,是创建时间 That's because Unices usually don't preserve the "original" creation time. 这是因为Unices通常不保留“原始”创建时间。

That said you can access all information that the OS provides with the stat module. 也就是说,您可以访问操作系统通过stat模块提供的所有信息。

The stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). stat模块定义常量和函数,以解释os.stat(),os.fstat()和os.lstat()的结果(如果存在)。 For complete details about the stat, fstat and lstat calls, consult the documentation for your system. 有关stat,fstat和lstat调用的完整详细信息,请查阅系统的文档。

stat.ST_CTIME stat.ST_CTIME
The “ctime” as reported by the operating system. 操作系统报告的“ ctime”。 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). 在某些系统(例如Unix)上,是上一次元数据更改的时间,而在其他系统(例如Windows)上,则是创建时间(有关详细信息,请参见平台文档)。

By lack of a good utility, I've created crtime . 由于缺乏好的工具,我创建了crtime

pip install crtime

Then you can use it like: 然后您可以像这样使用它:

sudo crtime ./

Would print: 将打印:

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

Note that for large directories it will be easily 1000x faster than xstat that is sometimes mentioned, as this creates a temporary file and then executes stat calls for all files at once. 请注意,对于大型目录,它有时会比有时提到的xstat快1000倍,因为这会创建一个临时文件,然后立即对所有文件执行stat调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM