简体   繁体   中英

Print lines between two dates from txt file Python

I have "transactions.txt" file like this:

1:5:iznos:15.02.2017.:usser
2:2:iznos:17.02.2017.:usser2
3:3:iznos:3.04.2017.:usser2
4:3:iznos:3.04.2017.:useer
5:7:iznos:5.05.2017.:usser2
6:3:iznos:16.06.2017.:usser3
7:8:iznos:18.06.2017.:usser

and function like this:

def date():
    start_date = input("Enter star date: ")
    date1 = date.strptime(start_date, "%d.%m.%Y.")
    end_date = input("Enter end date datum: ")
    date2 = date.strptime(end_date, "%d.%m.%Y.")
    if date1 > date2:
        print("Error:")
        date()
    elif date1 < date2:
        ### PRINT LINES BETWEEN THEESE TWO DATES        
date()

How to print transactions between two input dates?

PS Later I have to input two dates and username, then print transactions between two dates only for certain username. So, if someone could also help me with that... :)

you could try something like this:

from csv import reader
from io import StringIO  
from datetime import datetime


text = '''1:5:iznos:15.02.2017.:usser
2:2:iznos:17.02.2017.:usser2
3:3:iznos:3.04.2017.:usser2
4:3:iznos:3.04.2017.:useer
5:7:iznos:5.05.2017.:usser2
6:3:iznos:16.06.2017.:usser3
7:8:iznos:18.06.2017.:usser'''


from_date = datetime(2017, 4, 3)
to_date = datetime(2017, 5, 5)

# with open('data.txt', 'r') as file
with StringIO(text) as file:

    data = reader(file, delimiter=':')

    for line in data:
        date = datetime.strptime(line[3], '%d.%m.%Y.')

        if from_date <= date <= to_date:
            print(line)

First, you need to read the data; second, you need to extract date from every line; third, you need to check if the date is in wanted range; so the solution is:

with open('transactions.txt') as f:
    for line in f:
        l_date = date.strptime(line.split(':')[3], "%d.%m.%Y.")
        if date1 < l_date < date2:
            print line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM