Home > Net >  Converting a string into a date within a for loop
Converting a string into a date within a for loop

Time:06-08

I am trying to compare a date in a CSV file to days date - If todays date is bigger then the output will be no.

I am trying to figure out if the expiry date of a card is past todays date:

#input number you want to search
number = input('Enter the card number\n')
#read csv, and split on "," the line
   csv_file = csv.reader(open('carddetails.csv', "r"), delimiter=",")
#loop through the csv list
   for row in csv_file:
    #if current rows 2nd value is equal to input, print that row
      if number == row[1]:
         valid_to_date = row[3]
         if valid_to_date>todays_Date:
                     
            print("nop")
         else:
            print("yep")

I have declared todays_Date as a global variable else where.

It works in regards to giving me the date but it tells me that I cannot compare str and date.time. I haven't done much with datetime so looking how to convert valid_to_date to a date.time to be able to compare them.

CodePudding user response:

You're need to convert your string date to a datetime object with datetime.strptime

https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

# if your date in your csv is in format YYYYmmddTHHMMSS (year-month-day:hour-min-sec then
from datetime import datetime
valid_datetime = datetime.strptime(valid_to_date, "%Y%m%dT%H%M%S")

# now you can compare the datetimes
if valid_datetime > todays_date:
    valid = "NO"
  • Related