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


当前回答

你有几个选择。首先,你可以使用os.path.getmtime和os.path.getctime函数:

import os.path, time
print("last modified: %s" % time.ctime(os.path.getmtime(file)))
print("created: %s" % time.ctime(os.path.getctime(file)))

你的其他选择是使用os.stat:

import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print("last modified: %s" % time.ctime(mtime))

注意:ctime()不是指*nix系统上的创建时间,而是指inode数据最后一次更改的时间。(感谢kojiro在评论中提供了一个有趣的博客文章链接,使这一事实更加明确。)

其他回答

可能值得一看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

操作系统。Stat返回一个带有st_mtime和st_ctime属性的命名元组。在两个平台上,修改时间为st_mtime;不幸的是,在Windows中,ctime意味着“创建时间”,而在POSIX中它意味着“更改时间”。我不知道有什么方法可以在POSIX平台上获得创建时间。

最好的函数是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.path.getmtime和os.path.getctime函数:

import os.path, time
print("last modified: %s" % time.ctime(os.path.getmtime(file)))
print("created: %s" % time.ctime(os.path.getctime(file)))

你的其他选择是使用os.stat:

import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print("last modified: %s" % time.ctime(mtime))

注意:ctime()不是指*nix系统上的创建时间,而是指inode数据最后一次更改的时间。(感谢kojiro在评论中提供了一个有趣的博客文章链接,使这一事实更加明确。)

操作系统。Stat包含了创建时间。os.stat()中包含时间的元素没有st_anything的定义。

所以试试这个:

os.stat('feedparser.py')[8]

将其与ls -lah文件上的创建日期进行比较

它们应该是一样的。