nosensus
nosensus

Reputation: 1740

time and date in Python Language

I have log file

Thu Mar 22 21:14:36 2012; TCP;
Thu Mar 22 21:15:15 2012; TCP;
Thu Mar 22 21:16:23 2012; TCP;
Thu Mar 22 21:17:51 2012; TCP;
Thu Mar 22 21:18:45 2012; TCP;

I need to get logs for the last three minutes, the script must be in Python I tried to use datetime and slice function.

import datetime
x=datetime.datetime.now()
print x #result 2012-03-22 21:19:09.918804

But when I cut the date and leave only the time, the system generated an error

a=x[11:20]

...TypeError: 'datetime.datetime' object is unsubscriptable... I know that the algorithm should work well: the current time, take three minutes, but i don't have any ideas...but rather a lack of knowledge

Upvotes: 0

Views: 1225

Answers (2)

forivall
forivall

Reputation: 9891

When you call datetime.datetime.now() python returns a datetime object, not a string. That's why you can't take a slice from it directly. When you call print x, python internally calls str(x) to format it in the way you're seeing. So, you need a = str(x)[11:20].

However, a better solution is to use datetime.strftime.

As a segue from datetime.strftime, if you want to then get a datetime object from the your preexisting log file (in order to check check if the time has been in the last 3 minutes), you can use datetime.strptime like so: datetime.strptime(line.split(';',1)[0],"%a %b %H:%M:%S %Y).

Upvotes: 2

Danica
Danica

Reputation: 28846

datetime.datetime objects don't support slicing. What I think you're trying to do is str(x)[11:20]: that is, convert x to a string (which is what print x shows) and take the 11:20th indices of that.

Better might be to use strftime: x.strftime("%H:%M:%S").

But: once you have that string, you'll need to do some kind of comparison, and I'm not entirely sure how you're doing that. You might need to go in the other direction:

import datetime
import sys

cutoff = datetime.datetime.now() - datetime.timedelta(minutes=3)
line_format = "%a %b %d %H:%M:%S %Y; TCP;"

lines = iter(sys.stdin) # or iter(f) for a file object f

# skip all the lines before three minutes ago
for line in lines:
    logtime = datetime.datetime.strptime(line.strip(), line_format)
    if logtime >= cutoff:
        print line
        break

# print out the rest of the lines
for line in lines:
    print line

This could be made much fancier, but I think that'll do it. You might need to do some more string processing if the strptime format isn't exactly right, or the lines have actual content other than "TCP;".

Upvotes: 2

Related Questions