我正在尝试将CSV文件中的日期与天日期进行比较-如果今天的日期较大,则输出将为no。
我想知道一张卡的有效期是否超过了今天。
#input number you want to search
number = input('Enter the card numbern')
#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")
我已经将todays_Date
声明为全局变量else,其中
它在给我日期方面工作,但它告诉我不能比较str和date.time。我没有做过太多的datetime,所以看看如何将valid_to_date
转换为日期。是时候比较它们了
您需要使用datetime.strptime
将字符串date转换为datetime对象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"