user5566364
user5566364

Reputation: 173

inbuilt parser in Python for handling dates like : 05/May/2010:12:01:15 +0000

In a logfile, I have my date and time recorded in the format : [05/May/2010:12:01:15 +0000] I am trying to extract only the time from the above in Python3.x. I was mainly looking for a inbuilt parser in Python3.x. I ran into different formats except for this. I came up with a solution in JAVA using the below code and I am looking for something similar in Python3.x. Is there one ? Or do I have to write my own parser for extracting the date,time out of this ? Here is the JAVA code of what I wanted :

   //field[3] contains "[25/May/2015:23:11:15 +0000]"
   String timeStamp = fields[3].substring(1,fields[3].length()).split(" ")[0];
    SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.US);
    Date d = null;
    try {
        d = df.parse(timeStamp);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println("Time :"+ d.getTime());// Prints 23:11:15

Upvotes: 1

Views: 82

Answers (2)

user3657941
user3657941

Reputation:

Here is a solution using datetime.strptime:

from datetime import datetime

field3 = '[25/May/2015:23:11:15 +0000]'
result = datetime.strptime(field3, '[%d/%b/%Y:%H:%M:%S %z]')
print(result.strftime("%H:%M:%S"))

Output

23:11:15

Upvotes: 0

zwer
zwer

Reputation: 25789

You can use time.strptime() to parse it into a time.struct_time object:

import time

your_field = "[25/May/2015:23:11:15 +0000]"

parsed = time.strptime(your_field, "[%d/%b/%Y:%H:%M:%S %z]")
# NOTE: %z depends on implementation, you might need to remove the timezone info
# before parsing your date/time with `time.strptime()`.

# print time:
print(time.strftime("%H:%M:%S", parsed))
# prints: 23:11:15

But if you just want to get the time you don't need to parse it just to build it again, instead you can just substring it out:

your_field = "[25/May/2015:23:11:15 +0000]"

your_time = your_field.split(":", 1)[1].split(" ", 1)[0]

# print time:
print(your_time)
# prints: 23:11:15

Upvotes: 1

Related Questions