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()
dates | interviews | today_ts | today_date | |
---|---|---|---|---|
0 | 2023-06-01 | 185 | 2023-05-21 17:28:59.767052 | 2023-05-21 |
1 | 2023-06-02 | 138 | 2023-05-21 17:28:59.767052 | 2023-05-21 |
2 | 2023-06-05 | 137 | 2023-05-21 17:28:59.767052 | 2023-05-21 |
3 | 2023-06-06 | 192 | 2023-05-21 17:28:59.767052 | 2023-05-21 |
4 | 2023-06-07 | 137 | 2023-05-21 17:28:59.767052 | 2023-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:
dates | interviews | today_ts | today_date | delta | |
---|---|---|---|---|---|
0 | 2023-06-01 | 185 | 2023-05-21 17:28:59.767052 | 2023-05-21 | 11 days |
1 | 2023-06-02 | 138 | 2023-05-21 17:28:59.767052 | 2023-05-21 | 12 days |
2 | 2023-06-05 | 137 | 2023-05-21 17:28:59.767052 | 2023-05-21 | 15 days |
3 | 2023-06-06 | 192 | 2023-05-21 17:28:59.767052 | 2023-05-21 | 16 days |
4 | 2023-06-07 | 137 | 2023-05-21 17:28:59.767052 | 2023-05-21 | 17 days |