-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlogtimes.py
38 lines (30 loc) · 1.05 KB
/
logtimes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from datetime import datetime
import os
import urllib.request
SHUTDOWN_EVENT = 'Shutdown initiated'
# prep: read in the logfile
logfile = os.path.join('/tmp', 'log')
urllib.request.urlretrieve('http://bit.ly/2AKSIbf', logfile)
with open(logfile) as f:
loglines = f.readlines()
# for you to code:
def convert_to_datetime(line):
"""TODO 1:
Extract timestamp from logline and convert it to a datetime object.
For example calling the function with:
INFO 2014-07-03T23:27:51 supybot Shutdown complete.
returns:
datetime(2014, 7, 3, 23, 27, 51)
"""
return datetime.strptime(line.split()[1], "%Y-%m-%dT%X")
def time_between_shutdowns(loglines):
"""TODO 2:
Extract shutdown events ("Shutdown initiated") from loglines and
calculate the timedelta between the first and last one.
Return this datetime.timedelta object.
"""
datetimes = []
for line in loglines:
if SHUTDOWN_EVENT in line:
datetimes.append(convert_to_datetime(line))
return max(datetimes) - min(datetimes)