Home > Software design >  How do I find and compare dates in file?
How do I find and compare dates in file?

Time:08-07

I don't really know how exactly to explain this so please view the examples given I have a lot of lines but I'll just show 5.

A1234567, Amen, Mr, 18/01/1999, Construction, Head, 987654321, FullTime, 5000
A2345678, Bmen, Mr, 23/04/1994, Office, Worker, 987654321, FullTime, 3000
A3456789, Cwomen, Mrs, 13/01/1996, Aviation, Pilot, 987654321, FullTime, 4000
A4567890, Dmen, Mr, 18/01/2002, Construction, Assistant Head, 987654321, FullTime, 4500
A5678901, Ewomen, Ms, 18/01/1991, Construction, Worker, 987654321, FullTime, 2500

I want to get people that is AFTER year 1995 and deduct their salary (last value) by 10% so far i can do till

with open('list.txt') as file:
    for line in file:
        split = line.split(",")
        
        if split[3] < 1/1/1995:
          

the if statement is wrong, The result should be like this with everyone AFTER year 1995 with 10% deduction, those who are BEFORE 1995 are not touched

A1234567, Amen, Mr, 18/01/1999, Construction, Head, 987654321, FullTime, 4500
A2345678, Bmen, Mr, 23/04/1994, Office, Worker, 987654321, FullTime, 3000
A3456789, Cwomen, Mrs, 13/01/1996, Aviation, Pilot, 987654321, FullTime, 3600
A4567890, Dmen, Mr, 18/01/2002, Construction, Assistant Head, 987654321, FullTime, 4050
A5678901, Ewomen, Ms, 18/01/1991, Construction, Worker, 987654321, FullTime, 2500

CodePudding user response:

You should use datetimes.strptime

from datetime import datetime

with open('list.txt') as file:
    threshold = datetime(1995, 1, 1)

    for line in file:
        lines = line.split(",")
        
        salary = l[-1]
        date = datetime.strptime(l[3], "%d/%m/%Y")
        if date > threshold:
            print(salary * 0.9)

Since you are parsing a csv file you might have a look here

CodePudding user response:

Such manipulations are much easier once you parse your data into a propper datastructure. Then do your manipulation there and write out the result.

Your data looks like Pandas could help you here. And especially their csv parsing and writing. You would need to tell them about your delimiters and date structure, but once there you should have a table with numbers, strings dates etc.

Then you could query all the rows before a certain date and reduce the salary by 10%.

  • Related