首页 文章

如何在Python中创建文件和修改日期/时间?

提问于
浏览
739

我有一个脚本,需要根据文件创建和修改日期做一些事情,但必须在Linux和Windows上运行 .

在Python中获取文件创建和修改日期/时间的最佳方法是什么?

12 回答

  • 46
    >>> import os
    >>> os.stat('feedparser.py').st_mtime
    1136961142.0
    >>> os.stat('feedparser.py').st_ctime
    1222664012.233
    >>>
    
  • 2

    os.stat 确实包括创建时间 . 对于包含时间的 os.stat() 元素,没有st_anything的定义 .

    所以试试这个:

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

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

    它们应该是一样的 .

  • 623

    在Python 3.4及更高版本中,您可以使用面向对象的pathlib module接口,该接口包含大部分os模块的包装器 . 以下是获取文件统计信息的示例 .

    >>> import pathlib
    >>> fname = pathlib.Path('test.py')
    >>> assert fname.exists(), f'No such file: {fname}'  # check that the file exists
    >>> print(fname.stat())
    os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)
    

    有关 os.stat_result 包含的内容的更多信息,请参阅the documentation . 对于你想要的修改时间 fname.stat().st_mtime

    >>> import datetime
    >>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
    >>> print(mtime)
    datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)
    

    如果您想在Windows上创建时间,或者在Unix上更新最新的元数据,您可以使用 fname.stat().st_ctime

    >>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)
    >>> print(ctime)
    datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)
    

    This article有更多有用的信息和pathlib模块的示例 .

  • 37

    通过运行系统的stat命令并解析输出,我能够在posix上获得创建时间 .

    commands.getoutput('stat FILENAME').split('\"')[7]
    

    从终端(OS X)运行python外部的stat返回:

    805306374 3382786932 -rwx------ 1 km staff 0 1098083 "Aug 29 12:02:05 2013" "Aug 29 12:02:05 2013" "Aug 29 12:02:20 2013" "Aug 27 12:35:28 2013" 61440 2150 0 testfile.txt
    

    ...其中第四个日期时间是文件创建(而不是ctime更改时间,如其他注释所述) .

  • 11

    如果以下符号链接不重要,您也可以使用 os.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
    
  • 1

    你有几个选择 . 例如,您可以使用os.path.getmtimeos.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))
    

    Notectime() 不是指* nix系统上的创建时间,而是上次更改inode数据的时间 . (感谢kojiro通过提供一个有趣的博客文章的链接,在评论中更明确地说明了这一点)

  • 349
    import os, time, datetime
    
    file = "somefile.txt"
    print(file)
    
    print("Modified")
    print(os.stat(file)[-2])
    print(os.stat(file).st_mtime)
    print(os.path.getmtime(file))
    
    print()
    
    print("Created")
    print(os.stat(file)[-1])
    print(os.stat(file).st_ctime)
    print(os.path.getctime(file))
    
    print()
    
    modified = os.path.getmtime(file)
    print("Date modified: "+time.ctime(modified))
    print("Date modified:",datetime.datetime.fromtimestamp(modified))
    year,month,day,hour,minute,second=time.localtime(modified)[:-3]
    print("Date modified: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
    
    print()
    
    created = os.path.getctime(file)
    print("Date created: "+time.ctime(created))
    print("Date created:",datetime.datetime.fromtimestamp(created))
    year,month,day,hour,minute,second=time.localtime(created)[:-3]
    print("Date created: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
    

    版画

    somefile.txt
    Modified
    1429613446
    1429613446.0
    1429613446.0
    
    Created
    1517491049
    1517491049.28306
    1517491049.28306
    
    Date modified: Tue Apr 21 11:50:46 2015
    Date modified: 2015-04-21 11:50:46
    Date modified: 21/04/2015 11:50:46
    
    Date created: Thu Feb  1 13:17:29 2018
    Date created: 2018-02-01 13:17:29.283060
    Date created: 01/02/2018 13:17:29
    
  • 1

    以跨平台方式获取某种修改日期很简单 - 只需调用os.path.getmtime(path),您将获得上次修改 path 文件时的Unix时间戳 .

    另一方面,获取文件创建日期是繁琐且依赖于平台的,甚至在三个大型操作系统之间也是如此:

    Linux上的下一个最好的事情是通过os.path.getmtime()os.stat() 结果的.st_mtime属性访问文件的 mtime . 这将为您提供文件内容的最后修改时间,这可能适用于某些用例 .

    总而言之,跨平台代码应该看起来像这样......

    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
    
  • 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)
    
  • 383

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

    os.path.getmtime()

    getmtime (路径)
    返回上次修改路径的时间 . 返回值是一个数字,给出了自纪元以来的秒数(参见时间模块) . 如果文件不存在或无法访问,则引发os.error . 1.5.2版中的新功能 . 版本2.3中更改:如果os.stat_float_times()返回True,则结果为浮点数 .

    os.stat()

    stat (路径)
    在给定路径上执行stat()系统调用 . 返回值是一个对象,其属性对应于stat结构的成员,即:st_mode(保护位),st_ino(inode编号),st_dev(设备),st_nlink(硬链接数),st_uid(所有者的用户ID) ),st_gid(所有者的组ID),st_size(文件大小,以字节为单位),st_atime(最近访问的时间), st_mtime (最近一次内容修改的时间), st_ctime (取决于平台;最近元数据更改的时间)在Unix上,或在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 .

  • 0

    os.stat https://docs.python.org/2/library/stat.html#module-stat

    编辑:在较新的代码中你应该使用os.path.getmtime()(感谢Christian Oudard)
    但请注意,它返回一个浮点值time_t with fraction seconds(如果你的操作系统支持它)

  • -3

    os.stat 返回一个带有 st_mtimest_ctime 属性的命名元组 . 两个平台的修改时间均为 st_mtime ;不幸的是,在Windows上, ctime 表示"creation time",而在POSIX上表示"change time" . 我不知道有什么方法可以在POSIX平台上获得创建时间 .

相关问题