How to extract hour from the time

Viewed 201

I have a text file (in an email format) that I need to extract out the hours (in HH:MM:SS format). I initially split the text but can't seem to split the results again to grab the time only. If I do manage to isolate the time and try again, it provides me with

AttributeError: 'list' object has no attribute 'split'"

Text Sample

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

Here is my code

name = input('Enter File:')
input to default to mbox-short.txt
if len(name) < 1 : name = 'mbox-short.txt'
handle = open(name)

counts = dict()
for line in handle:
    line = line.rstrip()
    if line.startswith('From '):
        words = line.split()
        time = words[5:6]
        print(time)
        hour = time.split(':')
        print(hour)

The eventual goal is to build a histogram/time-series - any insights would be helpful to get past this part so I can continue!

4 Answers

When you do this:

time = words[5:6]

You are going to get a list back. Any time you get a "slice" of a list like this, it returns another list. So time is a list. You could "unpack" the list (which will always have just one element) like this:

[time] = words[5:6]

and then your code will work.

You are slicing a sequence (words[5:6]) and it will give you a sub-sequence, i.e. a shorter sequence of the same type as the original one. What you need to do get the element at position 5 is to use indexing notation: words[5] -- this will give you the element at that position alone.

It's because the result of string.split() is list. You need to pull the string that you want out of the list and then split that.

handle=['From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008']
for line in handle:
    line = line.rstrip()
    if line.startswith('From '):
        words = line.split()
        
        # time = words[5:6]
        # time=time[0] # extract the string

        # this is better than extracting yet another sub list though
        time = words[5]

        print(time)
        hour = time.split(':')
        print(hour)

output:

09:14:16
['09', '14', '16']

May I introduce you to Regular Expressions, or regex. This is a very useful sub-language used for text pattern matching - perfect for your hour extraction example.

Here is a link to an excellent online tool for testing/learning patterns.

For example:

Text string: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008

From your text string above you can write the pattern: (\d{2}):\d{2}:\d{2} to extract the hours. With the output being: 09.

Breakdown:

  • The () creates a 'capture group'; the set of values you want to extract.
  • \d matches any character which is a digit
  • {2} matches 2 of the previous tokens, in this case, a digit
  • : matches the literal ':' character

String it all together and you can match the time pattern of (2digits):2digits:2digits with the first set of 2digits being extracted.

In Python:

import re

text = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
exp = r'(\d{2}):\d{2}:\d{2}'

# Search for the pattern in the text string.
m = re.search(exp, text)
# Extract and print the first match (0 index) from the matches found.
print(m.groups()[0])

Output:

09

Related