在Mac上使用Python获取文件创建时间 [英] Get file creation time with Python on Mac

查看:434
本文介绍了在Mac上使用Python获取文件创建时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+.

对于在Mac上使用Python程序获取文件创建时间的方法,您有什么建议吗?

Do you have any suggestions on how to obtain the file creation time on the Mac in a Python program?

推荐答案

使用 st_birthtime 属性,原因是调用

Use the st_birthtime property on the result of a call to os.stat() (or fstat/lstat).

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

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

You can convert the integer result to a datetime object using datetime.datetime.fromtimestamp().

出于某种原因,当我第一次编写此答案时,我认为这不适用于Mac OS X,但是我可能会误会,即使是使用旧版本的Python,它现在也可以工作.以下是后代的旧答案.

使用ctypes访问系统调用stat64(适用于Python 2.5 +):

Using ctypes to access the system call stat64 (works with 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())

这篇关于在Mac上使用Python获取文件创建时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆