Skip to content

Commit c4047eb

Browse files
committed
Day 2: parse time delta from log file
1 parent 1071bcd commit c4047eb

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from datetime import datetime, timedelta
2+
3+
from logtimes import loglines, convert_to_datetime, time_between_shutdowns
4+
5+
6+
def test_convert_to_datetime():
7+
line1 = 'ERROR 2014-07-03T23:24:31 supybot Invalid user dictionary file'
8+
line2 = 'INFO 2015-10-03T10:12:51 supybot Shutdown initiated.'
9+
line3 = 'INFO 2016-09-03T02:11:22 supybot Shutdown complete.'
10+
assert convert_to_datetime(line1) == datetime(2014, 7, 3, 23, 24, 31)
11+
assert convert_to_datetime(line2) == datetime(2015, 10, 3, 10, 12, 51)
12+
assert convert_to_datetime(line3) == datetime(2016, 9, 3, 2, 11, 22)
13+
14+
15+
def test_time_between_events():
16+
diff = time_between_shutdowns(loglines)
17+
assert type(diff) == timedelta
18+
assert str(diff) == '0:03:31'

0 commit comments

Comments
 (0)