MacのPythonのos.path.getctime(およびUnixの一般的な)では、ファイルが作成された日付は表示されませんが、「最後の変更の時刻」少なくともドキュメント)。一方Finderでは、実際のファイル作成時間を見ることができるので、この情報はHFS +によって保持されます。MacでのPythonのファイル作成時間の取得
PythonプログラムでMacでのファイル作成時間を取得する方法はありますか?
MacのPythonのos.path.getctime(およびUnixの一般的な)では、ファイルが作成された日付は表示されませんが、「最後の変更の時刻」少なくともドキュメント)。一方Finderでは、実際のファイル作成時間を見ることができるので、この情報はHFS +によって保持されます。MacでのPythonのファイル作成時間の取得
PythonプログラムでMacでのファイル作成時間を取得する方法はありますか?
os.stat()
(またはfstat
/lstat
)への呼び出しの結果にst_birthtime
プロパティを使用します。
def get_creation_time(path):
return os.stat(path).st_birthtime
datetime.datetime.fromtimestamp()
を使用して整数結果をdatetimeオブジェクトに変換できます。
この回答が初めて書かれたときに何らかの理由でMac OS Xで動作するとは思われませんでしたが、私は誤解を招くかもしれないし、古いバージョンのPythonでも動作します。古い答えは後世のためのものです。 stat
ユーティリティを呼び出すためにsubprocess
を使用し
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
:
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など)では作成時刻はです。これは、通常、Unitsは「元の」作成時間を保持しないためです。
これは、OSが提供するすべての情報に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:/システムコール
stat64
(2.5+のPythonで動作します)にアクセスするためにを使用し/stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python –
@ S.Lott Mac上でファイルを作成する時間は本質的にクロスプラットフォームではないためです。 – Miles
@Miles:おそらく本当ですが、そこの答えはこの質問に完全に当てはまります。 –