I have a data frame with the following properties:
Column Non-Null Count Dtype --- ------ -------------- ----- 0 Date 226611 non-null object 1 Time 226611 non-null object 2 Code 226611 non-null object 3 Message 226611 non-null object
Date
column has values as format : 2021-11-28 00:00:00
and Time
column has values as format: 08:15:12.476000
. I am trying to create a DateTime
column with the following code (basically tried most of the available pandas’ methods like to_datetime, to_timestampe, etc.):
df["DateTime"] = pd.to_datetime(df["Date"]+" "+df["Time"])
but I keep getting the following error: unsupported operand type(s) for +: 'datetime.datetime' and 'str'
. Can someone point out what am I missing here? The expected output would be (restricting milliseconds to 2 digits only):
Date Time DateTime 0 2021-11-28 00:00:00 08:15:12.476000 2021-11-28 08:15:12.47
Advertisement
Answer
try concatenating by datetime parts
df["DateTime"] = pd.to_datetime(str(pd.to_datetime(df["Date"]).dt.date)+" "+str(pd.to_datetime(df["Time"]).dt.time))