python转换ls -l style date

时间:2015-05-19 12:20:45

标签: python

我有一些输出,如ls -l,即

drwxr-x---.   2 root   root     4.0K Nov 10  2014 sudoers.d
----------.   1 root   root     1.1K Nov 18 15:12 shadow-
-rw-r--r--.   1 root   root     1.7K Jan 13 21:18 motd
drwxr-xr-x.   2 root   root     4.0K Feb 13 15:29 snmp

使用python将日期/时间转换为某种可用格式(YYMMDD,纪元等)进行排序的最佳方法是什么?

我不能改变我给出的输出,所以必须使用它。

我确信之前已经解决了,但我似乎无法找到解决方案。如您所见,格式为:

%b %d %H:%M 

除非它超过6个月前,在这种情况下

%b %d %Y

我还没有尝试在代码中解决这个问题,因为我真的希望有一些实用功能我错过了某个地方,因为它是一种有点常见的格式。

2 个答案:

答案 0 :(得分:4)

  1. 对于每一行,抓取第四组和第七组空格之间的所有文本,以便您有一个字符串数组,如:"Nov 10 2014" "Nov 18 15:12"等。您可以使用正则表达式捕获此文本。

  2. 接下来,测试数组的每个元素是否包含:。这将告诉您是使用"%b %d %H:%M"还是"%b %d %Y"

  3. datetime.strptime与上述条件日期格式一起使用。

答案 1 :(得分:1)

使用glob和os.path.getmtime会为你解决这个问题

import os
import glob
# get the current working dir
path = os.getcwd()
files = glob.glob('%s/*' % path)
for file in files:
    #gets the modified time in epochs
    mtime = os.path.getmtime(file)
    print file, mtime