pythondatetimedayselapsed

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


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.


Solution

  • 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