python - 使用子进程 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
我怎样才能从上面的输出中得到日期?谢谢
解决方案
您可以使用正则表达式来搜索日期。
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())
推荐阅读
- javascript - 从格式化程序中触发功能?(响应式布局:折叠 > 切换列表)
- javascript - 无法使用 Node.js 为 AJAX 表单呈现内部 HTML
- drupal-8 - Drupal 8 如何更改段落格式?
- bash - Git blame 在 Gitlab CI 中提供的结果与在本地机器上不同
- heroku - 如何在 herokuapp 免费托管中进行 301 重定向?
- elasticsearch - FAIL: 'config' 配置失败,因为 UnavailableShardsException[[.opendistro_security][0] 主分片未激活
- javascript - 使用 Selenium webdriver 从下拉列表中选择值
- javascript - create-react-app 和 TypeScript 错误:使用 JSX 时“React”必须在范围内
- odoo - 如何根据条件 odoo 12 在选择字段上使用获取默认方法?
- html - 为什么背景有时显示有时不显示?