在Linux和Windows上获得文件创建和修改日期/时间的最佳跨平台方法是什么?
当前回答
以跨平台的方式获取某种修改日期很容易——只需调用os.path.getmtime(path),就会得到文件在path上最后一次修改的Unix时间戳。
另一方面,获取文件创建日期非常繁琐,而且依赖于平台,甚至在三大操作系统之间也有所不同:
On Windows, a file's ctime (documented at https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx) stores its creation date. You can access this in Python through os.path.getctime() or the .st_ctime attribute of the result of a call to os.stat(). This won't work on Unix, where the ctime is the last time that the file's attributes or content were changed. On Mac, as well as some other Unix-based OSes, you can use the .st_birthtime attribute of the result of a call to os.stat(). On Linux, this is currently impossible, at least without writing a C extension for Python. Although some file systems commonly used with Linux do store creation dates (for example, ext4 stores them in st_crtime) , the Linux kernel offers no way of accessing them; in particular, the structs it returns from stat() calls in C, as of the latest kernel version, don't contain any creation date fields. You can also see that the identifier st_crtime doesn't currently feature anywhere in the Python source. At least if you're on ext4, the data is attached to the inodes in the file system, but there's no convenient way of accessing it. The next-best thing on Linux is to access the file's mtime, through either os.path.getmtime() or the .st_mtime attribute of an os.stat() result. This will give you the last time the file's content was modified, which may be adequate for some use cases.
把这些放在一起,跨平台代码应该是这样的……
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
其他回答
如果下列符号链接不重要,也可以使用操作系统。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
可能值得一看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
os.stat
在更新的代码中,您可能应该使用os.path.getmtime()(谢谢,Christian Oudard)。
但是请注意,它返回一个带分数秒的浮点值time_t(如果您的操作系统支持它)。
以跨平台的方式获取某种修改日期很容易——只需调用os.path.getmtime(path),就会得到文件在path上最后一次修改的Unix时间戳。
另一方面,获取文件创建日期非常繁琐,而且依赖于平台,甚至在三大操作系统之间也有所不同:
On Windows, a file's ctime (documented at https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx) stores its creation date. You can access this in Python through os.path.getctime() or the .st_ctime attribute of the result of a call to os.stat(). This won't work on Unix, where the ctime is the last time that the file's attributes or content were changed. On Mac, as well as some other Unix-based OSes, you can use the .st_birthtime attribute of the result of a call to os.stat(). On Linux, this is currently impossible, at least without writing a C extension for Python. Although some file systems commonly used with Linux do store creation dates (for example, ext4 stores them in st_crtime) , the Linux kernel offers no way of accessing them; in particular, the structs it returns from stat() calls in C, as of the latest kernel version, don't contain any creation date fields. You can also see that the identifier st_crtime doesn't currently feature anywhere in the Python source. At least if you're on ext4, the data is attached to the inodes in the file system, but there's no convenient way of accessing it. The next-best thing on Linux is to access the file's mtime, through either os.path.getmtime() or the .st_mtime attribute of an os.stat() result. This will give you the last time the file's content was modified, which may be adequate for some use cases.
把这些放在一起,跨平台代码应该是这样的……
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
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
注意:在Linux上文件的ctime与在Windows上略有不同。 Windows用户把他们的时间称为“创建时间”。 Linux用户把他们的时间称为“改变时间”。
推荐文章
- 如何删除Python中的前导空白?
- python中的assertEquals和assertEqual
- 如何保持Python打印不添加换行符或空格?
- 为什么Python的无穷散列中有π的数字?
- Python 3.7数据类中的类继承
- 如何在PyTorch中初始化权重?
- 计数唯一的值在一列熊猫数据框架像在Qlik?
- 使用Pandas将列转换为行
- 从matplotlib中的颜色映射中获取单个颜色
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?