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