2017-08-19 130 views
0
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部分。我認爲這是因爲日期是字符串格式。如何比較日期從csv(字符串)到實際日期

+0

請加CSV內容 – PRMoureu

+0

https://pastebin.com/pN7pVdUN這裏的小樣本是CSV內容的範例 –

回答

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) 
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)