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

以跨平台方式获取某种修改日期很容易 – 只需调用

os.path.getmtime(path),您将获得上次修改路径上的文件时的Unix时间戳。

另一方面,获取文件创建日期是精巧和平台相关的,即使在三个大操作系统之间也不同:

>在Windows上,文件的ctime(记录在https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx)存储其创建日期。你可以通过调用os.stat()的os.path.getctime()或.st_ctime的属性在Python中访问这个。这将不能在Unix上运行,其中ctime is the last time that the file’s attributes or content were changed。

>在Mac上,以及一些其他基于Unix的操作系统,您可以使用调用os.stat()的结果的.st_birthtime属性。

>在Linux上,这是目前不可能的,至少没有为Python编写C扩展。虽然一些文件系统常用于Linux do store creation dates(例如,ext4将它们存储在st_crtime中),Linux内核offers no way of accessing them;特别是从C(从最后的内核版本,don’t contain any creation date fields)的stat()调用返回的结构。你也可以看到标识符st_crtime目前不在Python source的任何地方。至少如果你在ext4 ,数据被附加到文件系统中的inode,但是没有方便的方式来访问它。

Linux上下一个最好的事情是通过os.stat()结果的os.path.getmtime()或.st_mtime属性访问文件的mtime。这将给你最后一次文件的内容被修改,这可能是足够的一些用例。

把这一切放在一起,跨平台的代码应该看起来像这样…

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值