在 Python 中获取文件修改日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27580917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:58:28 来源:igfitidea点击:
Get file modification date in Python
提问by k_shil
I use the following code to get modification date of file if it exists:
如果文件存在,我使用以下代码获取文件的修改日期:
if os.path.isfile(file_name):
last_modified_date = datetime.fromtimestamp(os.path.getmtime(file_name))
else:
last_modified_date = datetime.fromtimestamp(0)
Is there a more elegant/short way?
有没有更优雅/更短的方式?
采纳答案by Martijn Pieters
You could use exception handling; no need to first test if the file is there, just catch the exception if it is not:
您可以使用异常处理;无需首先测试文件是否存在,如果不存在则捕获异常:
try:
mtime = os.path.getmtime(file_name)
except OSError:
mtime = 0
last_modified_date = datetime.fromtimestamp(mtime)
This is asking for forgiveness rather than permission.
这是请求宽恕而不是许可。