Creating a new datetime column in Pandas from an existing date

Viewed 1392

I am trying to create a new column in a Pandas DataFrame. The DataFrame contains a column called "date" and entries in the format of YYYY-MM-DD, e.g. 2021-06-11.

I am trying to add a new column which is 1 day after "date".

I can access individual entries e.g.

print(str(datetime.strptime(str(df["date"].iloc[0]), '%Y-%m-%d')+timedelta(days=1))[0:10]) 

2021-05-01

but I can't seem to create a new columnm:

df["mergeDate"]=str(datetime.strptime(str(df["date"]), '%Y-%m-%d')+timedelta(days=1))[0:10]

I get the following error:

raise ValueError("time data %r does not match format %r" % ValueError: time data '1 2021-04-29\n2 2021-04-28\n3 ...

I have checked my data and I can confirm that all of the data matches the specified format.

All help is appreciated,

C.

2 Answers

Let's consider a toy example -

df = pd.DataFrame({
    'date':pd.date_range(start='2021-06-01', periods=5)
})
df

Input

    date
0   2021-06-01
1   2021-06-02
2   2021-06-03
3   2021-06-04
4   2021-06-05

Code

If df.date is datetime type

df['mergeDate']= df.date + pd.Timedelta('1D')

If df.date is not of datetime type

df['mergeDate']= pd.to_datetime(df.date) + pd.Timedelta('1D')
df

Output

    date        mergeDate
0   2021-06-01  2021-06-02
1   2021-06-02  2021-06-03
2   2021-06-03  2021-06-04
3   2021-06-04  2021-06-05
4   2021-06-05  2021-06-06
df["mergeDate"]=pd.to_datetime(df["date"],format='%Y-%m-%d')
df["mergeDate"]=df["mergeDate"]+timedelta(days=1)

print(df)
Related