我有一个脚本,需要根据文件创建和修改日期做一些事情,但必须在Linux和Windows上运行.
在Python中获取文件创建和修改日期/时间的最佳跨平台方法是什么?
Bry*_*ley 659
你有几个选择.首先,您可以使用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)))
Run Code Online (Sandbox Code Playgroud)
您的另一个选择是使用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))
Run Code Online (Sandbox Code Playgroud)
注:ctime()不不指创建时间在*nix系统,而是最后一次inode的数据变化.(感谢kojiro通过提供一个有趣的博客文章的链接在评论中更清楚地说明这一事实)
Mar*_*ery 530
以跨平台的方式获取某种修改日期很简单 - 只需调用,您将获得上次修改文件时的Unix时间戳.os.path.getmtime(path)path
另一方面,获取文件创建日期是繁琐且依赖于平台的,甚至在三个大型操作系统之间也是如此:
ctime(记录在https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx)存储其创建日期.您可以通过Python访问它os.path.getctime()或.st_ctime调用结果的属性os.stat().这不适用于Unix,这ctime 是文件的属性或内容最后一次更改..st_birthtime调用结果的属性os.stat().在Linux上,目前这是不可能的,至少没有为Python编写C扩展.虽然一些常用于Linux的文件系统会存储创建日期(例如,ext4存储它们st_crtime),但Linux内核无法访问它们 ; 特别是,它从stat()C中的调用返回的结构,从最新的内核版本开始,不包含任何创建日期字段.您还可以看到标识符st_crtime当前不在Python源中的任何位置.至少如果你打开ext4,数据会附加到文件系统中的inode,但是没有方便的方法来访问它.
Linux上的下一个最好的事情是mtime通过结果的任一os.path.getmtime()或.st_mtime属性访问文件os.stat().这将为您提供文件内容的最后修改时间,这可能适用于某些用例.
总而言之,跨平台代码看起来应该是这样的......
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
Run Code Online (Sandbox Code Playgroud)
Chr*_*ard 368
用于此的最佳函数是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)
Run Code Online (Sandbox Code Playgroud)
用法示例:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
Mar*_*ett 47
os.stat https://docs.python.org/2/library/stat.html#module-stat
编辑:在较新的代码中你应该使用os.path.getmtime()(感谢Christian Oudard)
但请注意它返回一个浮点值time_t,其中包含分数秒(如果你的操作系统支持它)
Jay*_*Jay 38
有两种方法可以获得mod时间,os.path.getmtime()或os.stat(),但ctime不是可靠的跨平台(见下文).
getmtime(path)
返回上次修改路径的时间.返回值是一个数字,给出了自纪元以来的秒数(参见时间模块).如果文件不存在或无法访问,则引发os.error.1.5.2版中的新功能.版本2.3中更改:如果os.stat_float_times()返回True,则结果为浮点数.
stat(path)
在给定路径上执行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
>>>
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,您将使用statinfo.st_mtime或statinfo.st_ctime分别获取mtime和ctime.
mit*_*ndi 11
os.stat返回一个名为元组st_mtime和st_ctime属性.修改时间st_mtime在两个平台上; 不幸的是,在Windows上,ctime意味着"创建时间",而在POSIX上则意味着"改变时间".我不知道如何在POSIX平台上获得创建时间.
在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)
Run Code Online (Sandbox Code Playgroud)
有关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)
Run Code Online (Sandbox Code Playgroud)
如果要在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)
Run Code Online (Sandbox Code Playgroud)
本文提供了有关pathlib模块的更多有用信息和示例。
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))
Run Code Online (Sandbox Code Playgroud)
版画
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
Run Code Online (Sandbox Code Playgroud)