gpt4 book ai didi

python - 如何获取文件创建和修改日期/时间?

转载 作者:IT老高 更新时间:2023-10-28 11:58:50 40 4
gpt4 key购买 nike

获取文件创建和修改日期/时间的最佳跨平台方法是什么,适用于 Linux 和 Windows?

最佳答案

以跨平台方式获取某种修改日期很容易 - 只需调用 os.path.getmtime(<i>path</i>) 您将获得文件位于 path 时的 Unix 时间戳上次修改。

另一方面,获取文件创建日期是繁琐且依赖于平台的,即使在三大操作系统之间也存在差异:

将所有这些放在一起,跨平台代码应该看起来像这样......

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

关于python - 如何获取文件创建和修改日期/时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/237079/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com