XpreSS XpreSS - 4 years ago 212
Python Question

How to print line by date range

My program must print all lines in the range of my dates.
My file looks like this:

24/12/2015|5940.0
25/12/2015|5720.0
26/12/2015|8404.0
27/12/2015|9229.0
28/12/2015|8380.0
29/12/2015|6998.5
30/12/2015|10667.0
31/12/2015|8720.0


The first date is 28/12/2015, and the end date is 30/12/2015.

Expected:

28/12/2015 ---> 8380.0
29/12/2015 ---> 6998.5
30/12/2015 ---> 10667.0


Also in my file there will be same dates.
I heard I can use some python function for comparing the dates and print it , but I couldn't find it.

Answer Source

use strptime to convert string to datetime and use csv module to read the file data

import csv
from datetime import datetime

start = datetime(2015, 12, 28)
end   = datetime(2015, 12, 30)

with open("data.txt", "r") as f:
   r = csv.reader(f,delimiter ="|")


   for line in r:
      lineDate = datetime.strptime(line[0],"%d/%m/%Y")
      if start <= lineDate <=end :
         print("{0} ---> {1}".format(*line)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download