|
| 1 | +'''Extract datetimes from log entries and calculate the time |
| 2 | + between the first and last shutdown events''' |
| 3 | +from datetime import datetime |
| 4 | +import os |
| 5 | +import urllib.request |
| 6 | +import re |
| 7 | + |
| 8 | +SHUTDOWN_EVENT = 'Shutdown initiated' |
| 9 | + |
| 10 | +# prep: read in the logfile |
| 11 | +logfile = os.path.join('/tmp', 'log') |
| 12 | +urllib.request.urlretrieve('http://bit.ly/2AKSIbf', logfile) |
| 13 | + |
| 14 | +with open(logfile) as f: |
| 15 | + loglines = f.readlines() |
| 16 | + |
| 17 | + |
| 18 | +# for you to code: |
| 19 | + |
| 20 | +def convert_to_datetime(line): |
| 21 | + '''TODO 1: |
| 22 | + Given a log line extract its timestamp and convert it to a datetime object. |
| 23 | + For example calling the function with: |
| 24 | + INFO 2014-07-03T23:27:51 supybot Shutdown complete. |
| 25 | + returns: |
| 26 | + datetime(2014, 7, 3, 23, 27, 51)''' |
| 27 | + |
| 28 | + find_time = re.search('\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}', line) |
| 29 | + get_date = datetime.strptime(find_time.group(), '%Y-%m-%dT%H:%M:%S') |
| 30 | + |
| 31 | + # pass |
| 32 | + return get_date |
| 33 | + |
| 34 | + |
| 35 | +def time_between_shutdowns(loglines): |
| 36 | + '''TODO 2: |
| 37 | + Extract shutdown events ("Shutdown initiated") from loglines and calculate the |
| 38 | + timedelta between the first and last one. |
| 39 | + Return this datetime.timedelta object.''' |
| 40 | + |
| 41 | + first_event = None |
| 42 | + last_event = None |
| 43 | + for line in loglines: |
| 44 | + if 'Shutdown initiated' in line: |
| 45 | + if not first_event: |
| 46 | + first_event = line |
| 47 | + else: |
| 48 | + last_event = line |
| 49 | + |
| 50 | + get_first_event_time = re.search('\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}', first_event) |
| 51 | + first_event_time = datetime.strptime(get_first_event_time.group(), '%Y-%m-%dT%H:%M:%S') |
| 52 | + |
| 53 | + get_last_event_time = re.search('\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}', last_event) |
| 54 | + last_event_time = datetime.strptime(get_last_event_time.group(), '%Y-%m-%dT%H:%M:%S') |
| 55 | + |
| 56 | + time_delta = last_event_time - first_event_time |
| 57 | + # pass |
| 58 | + return time_delta |
| 59 | + |
0 commit comments