Skip to content
Advertisement

Get date using subprocess python?

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

JavaScript

and i get the output as

JavaScript

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:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement