Home > Net >  Place items from a list into a date class
Place items from a list into a date class

Time:03-31

I have a bunch of of dates in the format [yyyy, m, d] being pulled from a CSV column. I basically want to iterate through and turn all of those lists into "dates". Ive imported date, and I know that the date class takes 3 arguments (year, month, day). How Would i loop through and put the values from my list in as the arguments for the date class?

Below is my code. The CSV file has the first column filled with dates in the format mm/dd/yyyy, which I have already put into the yyyy/mm/dd interger format.

from datetime import date

from csv import reader
# open file in read mode
with open('food.csv',  encoding='utf-8-sig') as read_obj:
    # pass the file object to reader() to get the reader object
    csv_reader = reader(read_obj)
    # Iterate over each row in the csv using reader object
  
    for row in csv_reader:
        # row variable is a list that represents a row in csv
        
        date_str = row[0].replace('/',',')
        
        date_list = date_str.split(",")
        
        my_order = [2,0,1]
        date_list = [date_list[i] for i in my_order]
       
        for i in range(0, len(date_list)):
            date_list[i] = int(date_list[i])

            
                                
        exp_date = date(date_list[i])
        
        
        
       
        print(exp_list)

got error: TypeError: function missing required argument 'month' (pos 2)

CodePudding user response:

If the date class takes three arguments (year, month, day), then you should enter those three values when calling the class:

        exp_date = date(date_list[0], date_list[1], date_list[2])

where 0, 1 and 2 are the indices of the year, the month and the day respectively (I'm not sure which order is yours).

In your code, you only enter one argument, date_list[i]. Moreover, watch out for this i: it is not defined.

CodePudding user response:

If I understand your question correctly, maybe you can try Pandas.

import pandas as pd 
df = pd.read_csv('directory_to_food_csv_file\food.csv')
# errors='coerce': if any cell in the_date_column doesn't satisfy the format specified, pandas will turn it to missing
# format: you can find a list of datetime format in here: https://www.programiz.com/python-programming/datetime/strftime
df['the_date_column'] = pd.to_datetime(df['the_date_column'],errors='coerce',format='%m/%d/%Y')

Here is the link to Pandas to_datetime doc

  • Related