Skip to content

Commit d674e12

Browse files
authored
Create pybites_7.py
1 parent 2ef39dc commit d674e12

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

days/01-03 datetime/pybites_7.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from datetime import datetime
2+
import os
3+
import urllib.request
4+
5+
6+
def convert_to_datetime(line):
7+
"""TODO 1:
8+
Extract timestamp from logline and convert it to a datetime object.
9+
For example calling the function with:
10+
INFO 2014-07-03T23:27:51 supybot Shutdown complete.
11+
returns:
12+
datetime(2014, 7, 3, 23, 27, 51)
13+
"""
14+
timestamp = line.split()[1]
15+
line_datetime = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
16+
return line_datetime
17+
18+
19+
def time_between_shutdowns(loglines):
20+
"""TODO 2:
21+
Extract shutdown events ("Shutdown initiated") from loglines and
22+
calculate the timedelta between the first and last one.
23+
Return this datetime.timedelta object.
24+
"""
25+
L = [l for l in loglines if SHUTDOWN_EVENT in l]
26+
diff = [convert_to_datetime(y) - convert_to_datetime(x) for x,y in zip(L,L[1:])]
27+
#L=[]
28+
#for line in loglines:
29+
# if SHUTDOWN_EVENT in line:
30+
# dt = convert_to_datetime(line)
31+
# L.append(dt)
32+
#diff = [y - x for x,y in zip(L,L[1:])]
33+
return diff
34+
35+
36+
# prep: read in the logfile
37+
tmp = os.getenv("TMP", "/tmp")
38+
logfile = os.path.join(tmp, 'log')
39+
urllib.request.urlretrieve(
40+
'https://bites-data.s3.us-east-2.amazonaws.com/messages.log',
41+
logfile
42+
)
43+
44+
SHUTDOWN_EVENT = 'Shutdown initiated'
45+
46+
with open(logfile) as f:
47+
loglines = f.readlines()
48+
49+
print(time_between_shutdowns(loglines))

0 commit comments

Comments
 (0)