在Linux和Windows上获得文件创建和修改日期/时间的最佳跨平台方法是什么?


当前回答

最好的函数是os.path.getmtime()。在内部,这只是使用os.stat(filename).st_mtime。

datetime模块最适合操作时间戳,所以你可以像这样获得一个datetime对象的修改日期:

import os
import datetime
def modification_date(filename):
    t = os.path.getmtime(filename)
    return datetime.datetime.fromtimestamp(t)

使用的例子:

>>> d = modification_date('/var/log/syslog')
>>> print d
2009-10-06 10:50:01
>>> print repr(d)
datetime.datetime(2009, 10, 6, 10, 50, 1)

其他回答

如果下列符号链接不重要,也可以使用操作系统。lstat内置命令。

>>> os.lstat("2048.py")
posix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)
>>> os.lstat("2048.py").st_atime
1423378041.0

最好的函数是os.path.getmtime()。在内部,这只是使用os.stat(filename).st_mtime。

datetime模块最适合操作时间戳,所以你可以像这样获得一个datetime对象的修改日期:

import os
import datetime
def modification_date(filename):
    t = os.path.getmtime(filename)
    return datetime.datetime.fromtimestamp(t)

使用的例子:

>>> d = modification_date('/var/log/syslog')
>>> print d
2009-10-06 10:50:01
>>> print repr(d)
datetime.datetime(2009, 10, 6, 10, 50, 1)

os.stat

在更新的代码中,您可能应该使用os.path.getmtime()(谢谢,Christian Oudard)。

但是请注意,它返回一个带分数秒的浮点值time_t(如果您的操作系统支持它)。

有两个方法可以获得mod时间,os.path.getmtime()或os.stat(),但ctime跨平台不可靠(见下文)。

os.path.getmtime()

getmtime(路径) 返回最后一次修改路径的时间。返回值是一个给出 自epoch开始的秒数(请参阅time模块)。提高操作系统。如果文件存在,则错误 不存在或无法访问。1.5.2新版功能。在2.3版更改:如果 os.stat_float_times()返回True,结果是一个浮点数。

os.stat()

stat(path) Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>> 

在上面的例子中,您将使用statinfo。St_mtime或statinfo。St_ctime分别获取mtime和ctime。

可能值得一看crtime库,它实现了对文件创建时间的跨平台访问。

from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019