Denis McMahon denismfmcmahon at
Wed Aug 12 23:16:41 CEST 2015

On Wed, 12 Aug 2015 11:35:03 -0700, Ltc Hotspot wrote:

> How do I define time in the revised code ?

I'm guessing that you have a line of input like:

word word word timestamp word word word word

and that timestamp looks something like:


Start of by defining a list with 24 elements all integer 0.

Open the file.

for each line, first you trim it, then you split it on spaces, you take 
the relevant element of the list of bits as the timestamp, and then you 
split that on the ':' character, then you take the int value of the hours 
element of that list and use that as the index into your list to update 
the count.

Processing a file takes very few lines of actual code. There is no need 
to use a dictionary, you can do it with a single list and no sorting. 
This is a solution in 8 lines, and assumes that the actual requirement is 
to count, for each hour, the number of log messages generated in that 
hour, and then display, listed by hour, the number of messages generated 
in each hour during the day. It also assumes that there is a timestamp of 
the form hh:mm:ss that always appears at the same word position X in each 
line in the file, and that the hours record always at position Y in the 

c = [0 for i in range(24)]
f = open(filename,'r')
for l in f:
    h = int(l.strip().split()[X].split(':')[Y])
    c[h] = c[h] + 1
for i in range(24):
    print '{:02d} {}'.format(i, c[i])

Denis McMahon, denismfmcmahon at

More information about the Python-list mailing list