|
| 1 | +from datetime import datetime |
| 2 | +import os |
| 3 | +import urllib.request |
| 4 | +import re |
| 5 | + |
| 6 | +SHUTDOWN_EVENT = 'Shutdown initiated' |
| 7 | + |
| 8 | +# prep: read in the logfile |
| 9 | +print("cwd is {0}".format(os.getcwd())) |
| 10 | +logfile = os.path.join(os.getcwd(), '1LogFile.log') |
| 11 | + |
| 12 | +with open(logfile) as f: |
| 13 | + loglines = f.readlines() |
| 14 | + |
| 15 | + |
| 16 | +# for you to code: |
| 17 | + |
| 18 | +def convert_to_datetime(line): |
| 19 | + """TODO 1: |
| 20 | + Extract timestamp from logline and convert it to a datetime object. |
| 21 | + For example calling the function with: |
| 22 | + INFO 2014-07-03T23:27:51 supybot Shutdown complete. |
| 23 | + returns: |
| 24 | + datetime(2014, 7, 3, 23, 27, 51) |
| 25 | + """ |
| 26 | + print (line) |
| 27 | + time_regex = re.compile(r'(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})') |
| 28 | + mo = re.search(time_regex, line) |
| 29 | + date_string = '' |
| 30 | + datetime_obj = '' |
| 31 | + if mo: |
| 32 | + date_string = mo.group() |
| 33 | + |
| 34 | + print (date_string) |
| 35 | + if date_string: |
| 36 | + time = date_string.replace("T"," ") |
| 37 | + print ("The time in string format is {0}".format(time)) |
| 38 | + datetime_obj = datetime.strptime(time,"%Y-%m-%d %H:%M:%S") |
| 39 | + print (datetime_obj) |
| 40 | + return datetime_obj |
| 41 | + |
| 42 | +def time_between_shutdowns(loglines): |
| 43 | + """TODO 2: |
| 44 | + Extract shutdown events ("Shutdown initiated") from loglines and |
| 45 | + calculate the timedelta between the first and last one. |
| 46 | + Return this datetime.timedelta object. |
| 47 | + """ |
| 48 | + shutdown_regex = re.compile(r'supybot Shutdown initiated.$') |
| 49 | + logs_list = [] |
| 50 | + for line in loglines: |
| 51 | + mo = re.search(shutdown_regex, line) |
| 52 | + if mo: |
| 53 | + logline = mo.group() |
| 54 | + logs_list.append(line) |
| 55 | + print ("logs_list is {0}".format(logs_list)) |
| 56 | + datetime_obj1 = convert_to_datetime(logs_list[0]) |
| 57 | + datetime_obj2 = convert_to_datetime(logs_list[-1]) |
| 58 | + time_diff = (datetime_obj2 - datetime_obj1) |
| 59 | + print("time_diff is {0}".format(time_diff)) |
| 60 | + |
| 61 | + |
| 62 | +if __name__=="__main__": |
| 63 | + time_between_shutdowns(loglines) |
| 64 | + |
0 commit comments