I have a list of dates and I want to get a difference from a defined one(I mean days) and append days calculated in a new column
from datetime import date, datetime import pandas as pd df = pd.read_csv("date.csv", parse_dates = ["dates"]) #a date to substact dates in csv defined_date = date(2020,12,25) #a list of dates from a csv file csv_dates = df.dates diff = [defined_date - csv_dates] print(diff)
I get TypeError: unsupported operand type(s) for -: 'DatetimeArray' and 'datetime.date'
Now how can I read the dates in csv file in the same format as the defined date is there a way to do so
#How to change a list of dates from a csv file to date datatype csv_dates = df.dates
Advertisement
Answer
It is happening because you are trying to subtract array(series) from defined_date
. Which doesn’t work like that. You need to iterate over your csv_dates
series and add differences to the new column.
dates_diff = [] for d in csv_dates: dates_diff.append(d.date() - defined_date) df['diff'] = dates_diff