Jeroen De Rooy
Jeroen De Rooy

Reputation: 23

Python Pandas: Convert 2 fields Date + Time to 1 Datetime field

In a Pandas dataframe there are 2 columns:

"CREATED ON DATE" (dtype: datetime64[ns]) e.g. 2019-06-16
"CREATED AT TIME" (dtype: object) e.g. 19:46:14

Because of the type mismatch simply adding the field is not working.

df["CREATED DATETIME"] = df["CREATED ON DATE"] + df["CREATED AT TIME"]

How to combine these 2 columns as 1 datetime field "CREATED DATETIME"?

Upvotes: 2

Views: 52

Answers (1)

jezrael
jezrael

Reputation: 862581

Use to_timedelta:

df["CREATED DATETIME"] = df["CREATED ON DATE"] + pd.to_timedelta(df["CREATED AT TIME"])

If objects python times in column, convert it to strings before:

df["CREATED DATETIME"] = (df["CREATED ON DATE"] + 
                          pd.to_timedelta(df["CREATED AT TIME"].astype(str)))

Upvotes: 1

Related Questions