Home > database >  how to add a day to date column?
how to add a day to date column?

Time:08-11

I wanna add a day to all cells of this dataframe:

value       B   N   S      date   
date                    
2020-12-31  1   11  0   2020-12-31  
2021-01-01  3   80  0   2021-01-01  
2021-01-02  4   99  0   2021-01-02  
2021-01-03  3   78  0   2021-01-03  
2021-01-04  0   50  0   2021-01-04

to make it like this:

value       B   N   S      date   
date                    
2020-12-31  1   11  0   2021-01-01  
2021-01-01  3   80  0   2021-01-02  
2021-01-02  4   99  0   2021-01-03  
2021-01-03  3   78  0   2021-01-04  
2021-01-04  0   50  0   2021-01-05

how can I do this?

CodePudding user response:

df['date']=pd.to_datetime(df['date']).add(pd.offsets.Day(1))
df
    value   B   N   S   date
0   2020-12-31  1   11  0   2021-01-01
1   2021-01-01  3   80  0   2021-01-02
2   2021-01-02  4   99  0   2021-01-03
3   2021-01-03  3   78  0   2021-01-04
4   2021-01-04  0   50  0   2021-01-05

CodePudding user response:

You can temporarily convert to datetime to add a DateOffset:

df['date'] = (pd.to_datetime(df['date'])
                .add(pd.DateOffset(days=1))
                .dt.strftime('%Y-%m-%d') # optional
               )

Output:

         value  B    N  S         date
0   2020-12-31  1   11  0   2021-01-01
1   2021-01-01  3   80  0   2021-01-02
2   2021-01-02  4   99  0   2021-01-03
3   2021-01-03  3   78  0   2021-01-04
4   2021-01-04  0   50  0   2021-01-05
  • Related