How to add a column with the current date in pandas?

Follow this tutorial to add a date and time column into a pandas DataFrame.

Step 1: Acquire your data

You most probably have already a pandas DataFrame. However if not, here’s some data that you can use for this example:

import pandas as pd

# create two columns
dates = pd.Series(pd.date_range(start='6/1/23', periods=5,freq='B'))
interviews = [185, 138, 137, 192, 137]

# construct DataFrame
dates = pd.Series(pd.date_range(start='6/1/23', periods=5,freq='B'))
interviews = [185, 138, 137, 192, 137]

Step 2: Get the current datetime Timestamp as a column

You can easily get the current data and time Timestamp as a DataFrame column. THe following code adds as column named today_ts to our DataFrame:

today_ts = pd.Timestamp.today()
campaign['today_ts'] = today_ts

Alternatively, you can use the assign DataFrame method:

campaign = campaign.assign(today_ts = today_ts)

Step 3: Add a date column to your DataFrame

If you are interested to add just the date itself (without the time value) you can use the dt accessor for the relevant Series / Column:

campaign['today_date'] = pd.to_datetime(campaign['today_ts'].dt.date)

Here’s our DataFrame:

campaign.head()
datesinterviewstoday_tstoday_date
02023-06-011852023-05-21 17:28:59.7670522023-05-21
12023-06-021382023-05-21 17:28:59.7670522023-05-21
22023-06-051372023-05-21 17:28:59.7670522023-05-21
32023-06-061922023-05-21 17:28:59.7670522023-05-21
42023-06-071372023-05-21 17:28:59.7670522023-05-21

Step 4: Perform time calculations

Now that our data is complete we can easily perform some calculations, for example, subtracting times.

As an example, we can create a new column storing the calculated time difference between two days as following:

campaign['delta'] = campaign['dates'] - campaign['today_date']
campaign.head()

This will render the following data:

datesinterviewstoday_tstoday_datedelta
02023-06-011852023-05-21 17:28:59.7670522023-05-2111 days
12023-06-021382023-05-21 17:28:59.7670522023-05-2112 days
22023-06-051372023-05-21 17:28:59.7670522023-05-2115 days
32023-06-061922023-05-21 17:28:59.7670522023-05-2116 days
42023-06-071372023-05-21 17:28:59.7670522023-05-2117 days