Creating a new datetime column in Pandas from an existing date

  datetime, pandas, python

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-29n2 2021-04-28n3 …

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

All help is appreciated,

C.

Source: Python Questions

LEAVE A COMMENT