|
| 1 | +from datetime import datetime |
| 2 | +from datetime import timedelta |
| 3 | + |
| 4 | +import os |
| 5 | +import urllib.request |
| 6 | +import re |
| 7 | + |
| 8 | +SHUTDOWN_EVENT = 'Shutdown initiated' |
| 9 | + |
| 10 | +# prep: read in the logfile |
| 11 | +tmp = os.getenv("TMP", "/tmp") |
| 12 | +logfile = os.path.join(tmp, 'log') |
| 13 | +urllib.request.urlretrieve( |
| 14 | + 'https://bites-data.s3.us-east-2.amazonaws.com/messages.log', |
| 15 | + logfile |
| 16 | +) |
| 17 | + |
| 18 | +with open(logfile) as f: |
| 19 | + loglines = f.readlines() |
| 20 | + |
| 21 | +mydate=[] |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +def convert_to_datetime(line): |
| 27 | + """TODO 1: |
| 28 | + Extract timestamp from logline and convert it to a datetime object. |
| 29 | + For example calling the function with: |
| 30 | + INFO 2014-07-03T23:27:51 supybot Shutdown complete. |
| 31 | + returns: |
| 32 | + datetime(2014, 7, 3, 23, 27, 51) |
| 33 | + """ |
| 34 | + date_time_str = line.split(' ')[1] |
| 35 | + return (datetime.strptime(date_time_str, '%Y-%m-%dT%H:%M:%S')) |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +def time_between_shutdowns(loglines): |
| 40 | + """TODO 2: |
| 41 | + Extract shutdown events ("Shutdown initiated") from loglines and |
| 42 | + calculate the timedelta between the first and last one. |
| 43 | + Return this datetime.timedelta object. |
| 44 | + """ |
| 45 | + for i in loglines: |
| 46 | + if SHUTDOWN_EVENT in i: |
| 47 | + mydate.append(convert_to_datetime(i)) |
| 48 | + print (mydate[0],mydate[-1]) |
| 49 | + print (type(mydate[-1]-mydate[0])) |
| 50 | + return (mydate[-1]-mydate[0]) |
| 51 | + |
| 52 | +print (time_between_shutdowns(loglines)) |
0 commit comments