1
+ from datetime import datetime
2
+ import os
3
+ import urllib .request
4
+
5
+ SHUTDOWN_EVENT = 'Shutdown initiated'
6
+
7
+ # prep: read in the logfile
8
+ tmp = os .getenv ("TMP" , "/tmp" )
9
+ logfile = os .path .join (tmp , 'log' )
10
+ urllib .request .urlretrieve (
11
+ 'https://bites-data.s3.us-east-2.amazonaws.com/messages.log' ,
12
+ logfile
13
+ )
14
+
15
+ with open (logfile ) as f :
16
+ loglines = f .readlines ()
17
+
18
+ # for you to code:
19
+
20
+ def convert_to_datetime (line ):
21
+ """TODO 1:
22
+ Extract timestamp from logline 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
+ date_string = line .split (' ' )[1 ]
29
+ return datetime .strptime (date_string , '%Y-%m-%dT%H:%M:%S' )
30
+
31
+
32
+ def time_between_shutdowns (loglines ):
33
+ """TODO 2:
34
+ Extract shutdown events ("Shutdown initiated") from loglines and
35
+ calculate the timedelta between the first and last one.
36
+ Return this datetime.timedelta object.
37
+ """
38
+ for line in loglines :
39
+ if SHUTDOWN_EVENT in line :
40
+ start = convert_to_datetime (line )
41
+ break
42
+
43
+ for line in reversed (loglines ):
44
+ if SHUTDOWN_EVENT in line :
45
+ end = convert_to_datetime (line )
46
+ break
47
+
48
+ return end - start
0 commit comments