Create a column with TimeStamp from two other columns with date and time in a pandas DataFrame

Question:

I have the following dataframe in python:

     num_plate_ID     cam  entry_date entry_time 
0             XYA       2  2022-02-14   23:20:21     
1             JDS       2  2022-02-12   23:20:21    
2             OAP       0  2022-02-05   14:30:21   
3             ASI       1  2022-04-07   15:30:21  

Date and time are separated. I want to make a new column entry with both data joined in TimeStamp format. Resulting example:

     num_plate_ID     cam  entry_date entry_time                   entry
0             XYA       2  2022-02-14   23:20:21     2022-02-14 23:20:21
1             JDS       2  2022-02-12   23:20:21     2022-02-12 23:20:21  
2             OAP       0  2022-02-05   14:30:21     2022-02-05 14:30:21  
3             ASI       1  2022-04-07   15:30:21     2022-04-07 15:30:21  
Asked By: Carola

||

Answers:

A Simple Solution to your problem 🙂

data = {
    'num_plate_ID': ['XYA', 'JDS', 'OAP', 'ASI'],
    'cam': [2, 2, 0, 1],
    'entry_date': ['2022-02-14', '2022-02-12', '2022-02-05', '2022-04-07'],
    'entry_time': ['23:20:21', '23:20:21', '14:30:21', '15:30:21']
}

df = pd.DataFrame(data)

df['entry'] = df['entry_date'] + ' ' + df['entry_time']
df['entry'] = pd.to_datetime(df['entry'])

OUTPUT:

  num_plate_ID  cam  entry_date entry_time                entry
0          XYA    2  2022-02-14   23:20:21  2022-02-14 23:20:21
1          JDS    2  2022-02-12   23:20:21  2022-02-12 23:20:21
2          OAP    0  2022-02-05   14:30:21  2022-02-05 14:30:21
3          ASI    1  2022-04-07   15:30:21  2022-04-07 15:30:21

I hope this helps!

Answered By: Andrew

You can create a new entry column by:

import numpy as np
import pandas as pd


df = pd.DataFrame({'num_plate':'xcv',"entry_date":["2017-01-01"],"entry_time":["23:20:21"]})
df["entry"] = df["entry_date"]+" "+df["entry_time"]
print(df)
Answered By: Kiran S
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.