1

I am new to Python and I need to learn it for work purposes. I am having trouble figuring out a way to use Python to replace awk for column prints.

For example, I need to print out the date: root@user:~# date Mon Jun 24 01:30:08 EDT 2013

But, I only need a certain part of it: root@user:~# date | awk '{print $2" "$3" "$4" "$5}' Jun 24 01:30:54 EDT

Is there a way in Python to do this without needing to do the following: import os os.system("date | awk '{print $2" "$3" "$4" "$5}'")

I have tried to do an extensive Google/Bing/Ask/Yahoo search and have seemed to have come up short on this.

1 Answer 1

3

You probably want to look at the datetime.datetime.strftime() function for that particular task.

However, for the more general task of printing out certain fields, you'd use .split() and list slicing:

date_string = "Mon Jun 24 01:30:08 EDT 2013"
fields = date_string.split()
print ' '.join(fields[1:5]) # Prints "June 24 01:30:08 EDT"
Sign up to request clarification or add additional context in comments.

5 Comments

Amber, thanks for the response. This helps if I was looking to statically put in a date as string. What I am looking to do is, run the Linux "date" command and grab the state of it only print certain parts of it
@GregRobertDutertre Is there a reason you need to run the date command, as opposed to using the datetime library already built into Python?
Amber, I think it may be my naivety and I am so used to running that through Linux. I am currently reading up on the datetime function.
@GregRobertDutertre No worries. I think the datetime library (and specifically the strftime method I mentioned at the beginning of my answer) may do exactly what you need.
I figured out what I am looking for. I appreciate the input on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.