Home > database >  How can I add column with the dates (starting from today)?
How can I add column with the dates (starting from today)?

Time:11-20

How can I add to column C the dates (starting from today)? Column B is an example of what I want to get.

df = pd.DataFrame({'N': ['1', '2', '3', '4'], 'B': ['16.11.2021', '17.11.2021', '18.11.2021', '19.11.2021'], 'C': ['nan', 'nan', 'nan', 'nan']})

CodePudding user response:

If I understood your question correctly, you want something like this:

import datetime
base = datetime.datetime.today()
date_list = sorted([(base - datetime.timedelta(days=x)).strftime('%d.%m.%Y') for x in range(len(df))])
df['C'] = date_list

This will produce the same result as in column B.

CodePudding user response:

df.C = ((df.C.apply('rank', method='first') - 1) * pd.Timedelta(1, unit='D')
          pd.to_datetime("today")).dt.strftime('%d.%m.%Y')
print(df)

Prints:

   N           B           C
0  1  16.11.2021  19.11.2021
1  2  17.11.2021  20.11.2021
2  3  18.11.2021  21.11.2021
3  4  19.11.2021  22.11.2021
  • Related