Reputation: 1010
I have the following df:
date time
2018-01-01 00:00:00 7:30:33
2017-01-01 00:00:00 7:30:33
I want to create a datetime column that should look like this:
2018-01-01 7:30:33
2017-01-01 7:30:33
To do this I use the following code:
df["datetime"] = pd.to_datetime(df['date'].apply(str)+' '+df['time'])
It works the majority of the time. However, in some parts of my df (I dont know which parts), I get the following error:
ValueError: hour must be in 0..23
What am I doing wrong and how can I fix this?
Upvotes: 4
Views: 13702
Reputation: 403218
Convert date
to datetime
, and time
to timedelta
, and just sum 'em up.
pd.to_datetime(df.date) + pd.to_timedelta(df.time)
0 2018-01-01 07:30:33
1 2017-01-01 07:30:33
dtype: datetime64[ns]
If you're worried about invalid values, add the errors='coerce'
argument to both functions to handle them appropriately.
Upvotes: 5