如何计算日志文件条目每小时的访问量? [英] How to count accesses per hour from log file entries?
本文介绍了如何计算日志文件条目每小时的访问量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日志文件,其中每一行都包含IP地址,访问时间和所访问的URL.我想计算每小时的访问次数.
I have a log-file where every line contains IP address, time of access, and the URL accessed. I want to count the accesses per hour.
访问数据的时间看起来像这样
Time of access data looks like this
[01/Jan/2017:14:15:45 +1000]
[01/Jan/2017:14:15:45 +1000]
[01/Jan/2017:15:16:05 +1000]
[01/Jan/2017:16:16:05 +1000]
如何改进它,这样我就不需要每小时设置变量和if语句了?
How can I improve it so I don't need to set up the variable and if statement for every hour?
twoPM = 0
thrPM = 0
fouPM = 0
timeStamp = line.split('[')[1].split(']')[0]
formated_timeStamp = datetime.datetime.strptime(timeStamp,'%d/%b/%Y:%H:%M:%S %z').strftime('%H')
if formated_timeStamp == '14':
twoPM +=1
if formated_timeStamp == '15':
thrPM +=1
if formated_timeStamp == '16':
fouPM +=1
推荐答案
-
您可以将方括号包含在您的
strptime
格式说明中:
datetime.datetime.strptime(line.strip(),'[%d/%b/%Y:%H:%M:%S %z]')
您可以使用任何datetime.datetime
对象的.hour
属性提取小时:
You can extract the hour using the .hour
attribute of any datetime.datetime
object:
timestamp = datetime.datetime.strptime(…)
hour = timestamp.hour
您可以使用 collections.Counter
:
You can count the number of elements using a collections.Counter
:
from collections import Counter
def read_logs(filename):
with open(filename) as log_file:
for line in log_file:
timestamp = datetime.datetime.strptime(
line.strip(),
'[%d/%b/%Y:%H:%M:%S %z]')
yield timestamp.hour
def count_access(log_filename):
return Counter(read_logs(log_filename))
if __name__ == '__main__':
print(count_access('/path/to/logs/'))
这篇关于如何计算日志文件条目每小时的访问量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文