Camilla
Camilla

Reputation: 31

Dates manipulation in pandas dataframe

I have a column with dates in my dataframe, that comes from csv file. I would like to add an extra column with number of the days between the dates in the column in my csv file and a date of 6/1/2021. Here is my code:

output['Actual Days Difference']= output['date'] - '6/1/2021'

ValueError: Length of values (0) does not match length of index (1320)

and this code doesn't work. I need to subtract 6/1/2021 from every date that in my dataframe's column "date" Here is how my date column looks like in csv file:

date
7/15/2021
8/15/2021

Upvotes: 0

Views: 66

Answers (1)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

First cast your date to actual datetime and then get the difference of time

import pandas as pd

dataf = pd.DataFrame({'date':['7/15/2021', '8/15/2021']})


dataf["Actual Days Difference"] = (pd.to_datetime(dataf['date']) - pd.to_datetime('6/1/2021')).dt.days

print(dataf)
# output

# date  Actual Days Difference
# 0 7/15/2021   44
# 1 8/15/2021   75

Upvotes: 1

Related Questions