Skip to content
Advertisement

Get date using subprocess python?

I used subprocess to get information on a directory in my VM.

import subprocess

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

and i get the output as

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

How can i get just the date from the above output? Thank you

Advertisement

Answer

As an alternative, since you are already using a subprocess might as well use it all the way:

import subprocess

output = subprocess.getoutput("ssh -i /path-to-key ubuntu@IP ls -l /opt/orientdb/databases | awk -F' ' '{print $6, $7, $8}'")
print(output)

should get you output in the format:

Apr 25 2019

Jul 18 2019

etc.

So to explain what I did. I added the following to your command: "| awk -F' ' 'print{$6, $7, $8}'"

The first token: | is a pipe, which is basically saying use the output of the last command, in this case ls as the input for the next command, in this case awk

awk is awesome. In this case, what I’m doing is specifying a delimiter with -F ' ', saying to split the lines provided based on space. awk seems to handle the scenarios where there are multiple spaces well enough (Say between April_25 and Feb__2 for example)

then 'print{$6, $7, $8}' is saying that based on that delimiter, print out the 6th, 7th, and 8th columns, which should correspond to your month / day / year

From there it’s very simple date processing in python as mentioned in other answers. We’ll use the datetime library’s strptime function, which takes a string, and some format, and returns a datetime object you can manipulate and use. The format is pretty straightforward to use after you check out the format codes

lines = data.splitlines()
format = '%b %d  %Y'# Will parse strings like April 25 2019
# format = '%Y-%m-%d' will parse strings like 2019-04-25

for line in lines:
    date = datetime.strptime(line, format)
    print(date)
    # should get something like datetime.datetime(2019, 4, 25, 0, 0)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement