代码之家  ›  专栏  ›  技术社区  ›  Mark Biek

如何获取文件创建和修改日期/时间?

  •  1282
  • Mark Biek  · 技术社区  · 17 年前

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

    13 回复  |  直到 4 年前
        1
  •  2
  •   Delgan    7 年前

    以跨平台的方式获取某种修改日期很容易——只需致电 os.path.getmtime( path ) 您将获得文件在以下位置的Unix时间戳 path 最后一次修改。

    正在获取文件 创造 另一方面,日期复杂且依赖于平台,甚至在三大操作系统之间也有所不同:

    综上所述,跨平台代码应该是这样的。..

    import os
    import platform
    
    def creation_date(path_to_file):
        """
        Try to get the date that a file was created, falling back to when it was
        last modified if that isn't possible.
        See http://stackoverflow.com/a/39501288/1709587 for explanation.
        """
        if platform.system() == 'Windows':
            return os.path.getctime(path_to_file)
        else:
            stat = os.stat(path_to_file)
            try:
                return stat.st_birthtime
            except AttributeError:
                # We're probably on Linux. No easy way to get creation dates here,
                # so we'll settle for when its content was last modified.
                return stat.st_mtime
    
        2
  •  2
  •   Jim T. Tang    3 年前

    你有几个选择。首先,您可以使用 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 for making that fact more clear 在评论中提供一个有趣博客文章的链接。)