我的任务是处理如下所示的日志文件:
bob logged-in 11:21:01 pm
bob logged-out 11:23:22 pm
alice logged-in 11:24:12 pm
jane logged-in 11:31:00 pm
alice logged-out 11:34:20 pm
jane logged-out 11:55:00 pm
bob logged-n 11:56:01 pm等等。
我需要创建一个脚本,显示他们的平均登录时间。输出应该如下所示:
jane: 12.5 mins
alice: 2.3 mins
bob: 2.2 mins 一个用户可以多次登录。文件按时间排序,登录/注销条目不是连续的。
我正在寻找解决这个问题的bash或python解决方案,即使没有解决困难的时间戳的问题(假设我已经找到了将这样的部分时间戳转换为纪元格式的方法)。
任何帮助都将不胜感激。
发布于 2018-09-24 18:31:51
假设用户每次登录后都要注销,然后才能再次登录,您可以这样做。
进行2次循环第一次循环捕获所有登录,第二次循环捕获所有注销
您的设置应如下所示:
from datetime import datetime
from functools import reduce
lines = []
with open('logs.txt', 'r') as f:
lines = f.readlines()
times = {}您的第一个循环应该如下所示:
for i in range(len(lines)):
split_login = lines[i].split(' ')
if split_login[1] != 'logged-in':
continue
name = split_login[0]
# take the login time from the splitted line
login_time = split_login[2] + split_login[3].replace('\n', '')
# converted to datetime object
login_time = datetime.strptime(login_time, '%I:%M:%S%p')
# create dictionary in times dictionary where you store time per user
if name not in times:
times[name] = {'times': [], 'avg': 0}现在,第二个循环应该是一个内部循环,它将从第一个循环所在的索引开始。
for ii in range(len(lines)):
if i+ii+1 < len(lines):
split_logout = lines[ii+i+1].split(' ')
if split_logout[0] == name:
# take the logout time from the splitted line
logout_time = split_logout[2] + split_login[3].replace('\n', '')
# convert to datetime object
logout_time = datetime.strptime(logout_time, '%I:%M:%S%p')
# calc how long the login was
time_logged = logout_time - login_time
# append to the times of the user
times[name]['times'].append(time_logged.total_seconds())
# get the average
times[name]['avg'] = reduce(lambda x, y: x + y, times[name]['times']) / len(times[name]['times'])
break
#print the avg times per user
for k, v in times.items():
print('%s: %d' % (k, v['avg']/60))这只是一个快速和肮脏的例子,我相信有更好的方法,当然可以清理代码,因为有一些重复的代码。
https://stackoverflow.com/questions/52476639
复制相似问题