简体   繁体   中英

how to compare a date from a csv file with a variable in python

I have a function where I can read out my csv file. In my csv I have the following 2 information. the studentnumber and when the student passed the exam. I need to know which students have passed the exam in less then 4 weeks. How could I compare these 2 with eachother? the dates that I have in my csv file looks something like this: 21-10-2020 15:20

row[0] = studentsname

row[12] = passed date

I have tried doing something like this where I compare row[12] with the end_date but then I get an error message saying this

Error code:

'<' not supported between instances of 'str' and 'datetime.datetime'

My code:

from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file, 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            allPassedStudents.append(row[0])
            if row[12] < end_date:
                fastStudent.append[row[0]]
                print(fastStudent)

You are comparing variables that are of different types. To compare a string to a date you must convert one to a date or the other to a string. In this case you want to convert it to a date

from datetime import datetime
date_string = '2021-12-31'
datetime = datetime.strptime(date_string, '%Y-%m-%d')
print(datetime)

datetime documentation for other string formats

That's because row[12] is a str , not datetime .

  1. need to change a type of row[12] to datetime, using datetime.strptime . In this case, you shoud use a format '%d-%m-%Y %H:%M' for '21-10-2020 15:20', for example.

  2. fastStudent.append[row[0]] -> need to be changed to fastStudent.append(row[0]) .

import csv
from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file", 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        print(row)
        passedDate = datetime.strptime(row[12], '%d-%m-%Y %H:%M') # to convert a type of row[12] to datetime type, to enable it comparable!
        if passedDate:
            allPassedStudents.append(row[0])
            if passedDate < end_date:
                fastStudent.append(row[0]) # -> I changed [] to ()
                print(fastStudent)
                # ['Tommy'] (for exmample)

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