首页 > 解决方案 > 使用子进程 python 获取日期?

问题描述

我使用 subprocess 来获取有关我的 VM 中目录的信息。

import subprocess

output = subprocess.getoutput("ssh -i /path-to-key ubuntu@IP ls -l /opt/orientdb/databases")
print(output)

我得到的输出为

drwxr-xr-x 2 root root  4096 Apr 25  2019 friendship_graph_434
drwxr-xr-x 2 root root  4096 Jul 18  2019 friendship_graph_453
drwxr-xr-x 2 root root  4096 Sep  3  2019 friendship_graph_465
drwxr-xr-x 2 root root  4096 Oct  2  2019 friendship_graph_468
drwxr-xr-x 2 root root  4096 Oct  4  2019 friendship_graph_471
drwxr-xr-x 2 root root  4096 Oct 15  2019 friendship_graph_477
drwxr-xr-x 2 root root  4096 Nov  6  2019 friendship_graph_471
drwxr-xr-x 2 root root  4096 Apr 29  2020 friendship_graph_496
drwxr-xr-x 2 root root  4096 Nov 27  2019 friendship_graph_497
drwxr-xr-x 2 root root  4096 Dec  3  2019 friendship_graph_49
drwxr-xr-x 2 root root  4096 Dec  4  2019 friendship_graph_498

我怎样才能从上面的输出中得到日期?谢谢

标签: pythonsubprocess

解决方案


您可以使用正则表达式来搜索日期。

from datetime import datetime
import re

pattern = re.compile(
    r"\b((?:(?:Jan)|(?:Feb)|(?:Mar)|(?:Apr)|(?:May)|(?:Jun)|(?:Jul)|(?:Aug)|(?:Sep)|(?:Oct)|(?:Nov)|(?:Dec))\s+\d\d?\s+(?:[12]\d\d\d))\b"
)

format = '%b %d  %Y'

data = '''\
drwxr-xr-x 2 root root  4096 Apr 25  2019 friendship_graph_434
drwxr-xr-x 2 root root  4096 Jul 18  2019 friendship_graph_453
drwxr-xr-x 2 root root  4096 Sep  3  2019 friendship_graph_465
drwxr-xr-x 2 root root  4096 Oct  2  2019 friendship_graph_468
drwxr-xr-x 2 root root  4096 Oct  4  2019 friendship_graph_471
drwxr-xr-x 2 root root  4096 Oct 15  2019 friendship_graph_477
drwxr-xr-x 2 root root  4096 Nov  6  2019 friendship_graph_471
drwxr-xr-x 2 root root  4096 Apr 29  2020 friendship_graph_496
drwxr-xr-x 2 root root  4096 Nov 27  2019 friendship_graph_497
drwxr-xr-x 2 root root  4096 Dec  3  2019 friendship_graph_49
drwxr-xr-x 2 root root  4096 Dec  4  2019 friendship_graph_498
'''

lines = data.splitlines()
for line in lines:
    m = pattern.search(line)
    s = m.group(1)
    d = datetime.strptime(s, format)
    print(d.date())

推荐阅读