adding integer column to date column to get 'future date' using python

2.1k Views Asked by At

I have a python dataframe with a 'date' column with ~200 elements in the format yyyy-mm-dd.

I have a 2nd column (in the same dataframe) with the number of days (these days vary...sometime 1, sometime 360), but always integers.

I want to add the two up.

The date column is of type datetime64 [ns], and 'days' column is type int64.

truely stuck. I Can find lots of examples where the days are constant, but nothing where the days are in a column.

Please help.

2

There are 2 best solutions below

4
instinct246 On BEST ANSWER

Is this what you are looking for? Pandas has its own date time and timedelta module to make things easier.

Sample Dataframe:

df = pd.DataFrame({'Dates_Col':['2019-12-15','2020-01-14','2020-03-19','2020-06-17','2019-08-12'], 'Days':[2,15,70,28,3]})
df

O/P

enter image description here

Code to add days from second column to the first column:

df['Dates_Col'] = pd.to_datetime(df['Dates_Col']) #Convert the first column to pandas datetime type
df['Dates_Col'] = df['Dates_Col']+pd.to_timedelta(df['Days'],unit='d') #Convert the second column type to pandas timedelta type and add to first column (which is already in date time type)
df

O/P

enter image description here

2
Parakiwi On

date.timedelta is what you are after

you can use this to specify the number of days (or other time/date increments)

date = datetime.date(2030, 2, 2)
days = datetime.timedelta(2)
print(date + days)

Alternatively, if you are using numpy, timedelta will do the same conceptual thing for a datetime64 type