Как мне сделать так, чтобы 18 февраля 2016 г. было меньше 1 марта 2016 г. в python? - PullRequest
0 голосов
/ 05 мая 2020
import os
import re 
from collections import Counter 
from collections import OrderedDict 
from datetime import datetime

currentDirectoryPath = os.getcwd()
print(currentDirectoryPath)


regexp = re.compile(
    r'(?P<clientIP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+\['
    + '(?P<timestamp>\d{2}/[A-Z][a-z]{2}/\d\d\d\d).+\"'
    + '(?P<action>[A-Z]{3,4}).+\"'  
    + '\s*(?P<statuscode>[1-5][0-9][0-9])'
    )



os.chdir("/content/drive/My Drive/IT 170/log")
currentDirectoryPath = os.getcwd()
listOfFileNames = os.listdir(currentDirectoryPath)
for files in listOfFileNames :
  print(files) 

nLogUser = input ("What file do you want to read? (digit) ")
print('access_'+ nLogUser  +'.log')
f = open('access_'+ nLogUser  +'.log', 'r')
matched = 0
failed = 0
cnt_clientIPs = Counter()
cnt_clientIPsP1 = Counter()
cnt_clientIPsP2 = Counter()


def TopClientIp():
  startdateInput = input("What date would you like to start at? (dd/Mmm/yyyy) ")
  enddateInput= input("What date would you like to end at? (dd/Mmm/yyyy) ")
  f = open('access_'+ nLogUser  +'.log', 'r')
  allLines=f.readlines()
  for line in allLines:
    m = re.match(regexp,line)
    if m:
      if  m.group('timestamp') >= startdateInput and  m.group('timestamp') <= enddateInput:
        cnt_clientIPsP1.update([m.group('clientIP')])
    else:
      continue



userChoice=input(" \n Welcome to the Log Analyzer program! Here we have some choices on what you would like to see. \n If you would like to see the Top IP addresses enter 1. \n")
if userChoice == "1":
  userInputIP = input("Enter how many of the top clients you want to see. ")
  userInput=input("Would you like to see all clients from a certian date? (Yes or no)")
  if userInput.lower() == "yes":
    TopClientIp()
    #After creating the counter for the specific time range this new counter will print the Clients IP in the time range
    for clientIP, count in cnt_clientIPsP1.most_common(int(userInputIP)):
      print('[*] %30s: %d' % (clientIP, count)) 
    print('[*] ============================================')
  else:
#This one prints from all time. 
    print('[*] ============================================')
    print('[*] '+ userInputIP +' Most Frequently Occurring Clients Queried')
    print('[*] ============================================')
    for clientIP, count in cnt_clientIPs.most_common(int(userInputIP)):
      print('[*] %30s: %d' % (clientIP, count))
    print('[*] ============================================')


Enter how many of the top clients you want to see. 10
[*] ============================================
[*] 10 Most Frequently Occurring Clients Queried
[*] ============================================
[*]                 205.167.170.15: 15695
[*]                  79.142.95.122: 3207
[*]                  52.22.118.215: 734
[*]                  84.112.161.41: 712
[*]                   37.1.206.196: 371
[*]                   91.200.12.22: 287
[*]                178.191.155.244: 284
[*]                 198.50.160.104: 249
[*]                   84.115.10.14: 234
[*]                  93.83.250.186: 219
[*] ============================================

 Welcome to the Log Analyzer program! Here we have some choices on what you would like to see. 
 If you would like to see the Top IP addresses enter 1. 
 If you would like to see the top actions enter 2. 
 If you would like to see the top clients of a certian status code enter 3. 
 If you would like to see the top client with a specific action and status code enter 4.1
Enter how many of the top clients you want to see. 10
Would you like to see all clients from a certian date? (Yes or no)yes
What date would you like to start at? (dd/Mmm/yyyy) 18/Feb/2016
What date would you like to end at? (dd/Mmm/yyyy) 01/Mar/2016
[*] ============================================
[*] 10 Most Frequently Occurring Clients Queried
[*] ============================================
[*] ============================================

Я читаю файл и хочу выбрать дату между двумя датами. В качестве примера я могу распечатать это, когда дни начала и окончания увеличиваются. 10 февраля 2018 года, начало - 13 февраля 2018 года. Но как я могу это сделать, если день окончания - 01 марта 2018 года, а день начала - 10 февраля 2018 года? Как вы можете видеть выше в коде.

def TopClientIp():
  startdateInput = input("What date would you like to start at? (dd/Mmm/yyyy) ")
  enddateInput= input("What date would you like to end at? (dd/Mmm/yyyy) ")
  f = open('access_'+ nLogUser  +'.log', 'r')
  allLines=f.readlines()
  for line in allLines:
    m = re.match(regexp,line)
    if m:
      if  m.group('timestamp') >= startdateInput and  m.group('timestamp') <= enddateInput:
        cnt_clientIPsP1.update([m.group('clientIP')])
    else:
      continue

Я считаю, что оператор If для m.group () написан неправильно.

1 Ответ

0 голосов
/ 05 мая 2020

Вы можете попробовать это:

>>> d1 = datetime.datetime.strptime( '18/Feb/2016', '%d/%b/%Y')
>>> d1
datetime.datetime(2016, 2, 18, 0, 0)
>>> d2 = datetime.datetime.strptime( '01/Mar/2016', '%d/%b/%Y')
>>> d2
datetime.datetime(2016, 3, 1, 0, 0)
>>> d1 < d2
True
>>> 
...