首页 > 解决方案 > 在 Python 中提取文件的创建时间

问题描述

我需要提取文件的创建时间。但不是日期。作为在以下位置创建的文件的示例:

2018 年 7 月 31 日星期二 22:48:58

代码应打印1368(结果来自:22 小时*60+24 分钟)

我得到了以下程序,它运行良好,但在我看来很丑。

import os, time

created=time.ctime(os.path.getctime(filename)) # example result: Tue Jul 31 22:48:58 2018
hour=int(created[11:13])
minute=int(created[14:16])
minute_created=hour*60+minute

print (minute_created)

因为我喜欢编写漂亮的代码,所以我的问题是:在 Python 中是否有更优雅的方法?

标签: pythonpython-3.xfiletimeminute

解决方案


使用正则表达式:

import os, time, re

time = time.ctime(os.path.getctime(filename))
hours, mins, secs = map(int, re.search(r'(\d{2}):(\d{2}):(\d{2})', time).groups())
minutes_created = hours*60+mins
minutes_created_fr = minutes_created + secs/60 # bonus with fractional seconds

推荐阅读