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

我有一个脚本,该脚本需要根据文件创建和修改日期执行一些操作,但必须在Linux和Windows上运行。

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


#1楼

最好的功能是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)

#2楼

通过运行系统的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

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


#3楼

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

编辑:在较新的代码中,您可能应该使用os.path.getmtime() (感谢Christian Oudard)
但是请注意,它返回的time_t浮点值只有小数秒(如果您的操作系统支持)


#4楼

您有两种选择。 首先,可以使用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))

注意ctime() 不是在* nix系统上引用创建时间,而是在inode数据最后一次更改时。 (感谢kojiro通过提供指向有趣的博客文章的链接使评论中的事实更加清楚)


#5楼

有两种获取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()

statpath
在给定路径上执行stat()系统调用。 返回值是一个对象,其属性与stat结构的成员相对应,即:st_mode(保护位),st_ino(索引节点号),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。


#6楼

os.stat返回具有st_mtimest_ctime属性的命名元组。 在两个平台上,修改时间均为st_mtime 。 不幸的是,在Windows上, ctime表示“创建时间”,而在POSIX上则表示“更改时间”。 我不知道有什么方法可以在POSIX平台上获得创建时间。


#7楼

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

#8楼

如果遵循符号链接并不重要,则也可以使用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

#9楼

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

所以试试这个:

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

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

它们应该是相同的。


#10楼

) and you'll get the Unix timestamp of when the file at path was last modified. 以跨平台的方式获取某种修改日期很容易-只需调用os.path.getmtime( ) ,您将获得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

#11楼

在Python 3.4及更高版本中,您可以使用面向对象的pathlib模块接口,该接口包括许多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包含的内容的更多信息,请参考文档 。 对于修改时间,您需要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)

本文提供了有关pathlib模块的更多有用信息和示例。


#12楼

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

#13楼

可能值得看看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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值