如何比较从csv(字符串)到实际日期的日期

时间:2017-08-19 17:58:43

标签: python csv date

filenameA ="ApptA.csv" 
filenameAc = "CheckoutA.csv"

def checkouttenantA():
    global filenameA
    global filenameAc
    import csv
    import datetime
    with open(filenameA, 'r') as inp, open(filenameAc, 'a' , newline = "") as out:
        my_writer = csv.writer(out)
        for row in csv.reader(inp):
            my_date= datetime.date.today()
            string_date = my_date.strftime("%d/%m/%Y")
            if row[5] <= string_date:
                my_writer.writerow(row)

日期以格式%d /%m /%Y保存在列[5]上的Excel文件中。我试图将csv文件中的日期与实际日期进行比较,但它只是比较%d部分。我认为这是因为日期是字符串格式。

2 个答案:

答案 0 :(得分:2)

好的,所以也有一些改进,我将其作为编辑,但你将今天的日期转换为strftime()的字符串并比较两个字符串,你应该将字符串日期从csv文件转换为datetime对象并进行比较。

我会添加大量的评论来尝试解释代码及其背后的原因。

# imports should go at the top
import csv

# notice we are importing datetime from datetime (we are importing the `datetime` type from the module datetime
import from datetime import datetime

# try to avoid globals where possible (they're not needed here)

def check_dates_in_csv(input_filepath):
    ''' function to load csv file and compare dates to todays date'''

    # create a list to store the rows which meet our criteria
    # appending the rows to this will make a list of lists (nested list)
    output_data = []

    # get todays date before loop to avoid calling now() every line
    # we only need this once and it'll slow the loop down calling it every row
    todays_date = datetime.now()

    # open your csv here using the function argument
    with open(input_filepath, output_filepath) as csv_file:
        reader = csv.reader(csv_file)

        # iterate over the rows and grab the date in each row
        for row in reader:
            string_date = row[5]

            # convert the string to a datetime object
            csv_date = datetime.strptime(string_date, '%d/%m/%Y')

            # compare the dates and append if it meets the criteria
            if csv_date <= todays_date:
                output_data.append(row)

         # function should only do one thing, compare the dates
         # save the output after
         return output_data

# then run the script here
# this comparison is basically the entry point of the python program
# this answer explains it better than I could: https://stackoverflow.com/questions/419163/what-does-if-name-main-do
if __name__ == "__main__":

    # use our new function to get the output data
    output_data = check_dates_in_csv("input_file.csv")

    # save the data here
    with open("output.csv", "w") as output_file:
        writer = csv.writer(output_file)
        writer.writerows(output_data)

答案 1 :(得分:0)

我建议使用Pandas执行此类任务:

import pandas as pd

filenameA ="ApptA.csv" 
filenameAc = "CheckoutA.csv"
today = pd.datetime.today()

df = pd.read_csv(filenameA, parse_dates=[5])
df.loc[df.iloc[:, 5] <= today].to_csv(filenameAc, index=False)