Reputation: 303
I have a dataframe with two columns: 1 timedelta 'Time', and 1 datetime 'DateTime'.
My timedelta column simply contains/displays a normal regular time, it never has more than 24 hours. It's not being used as a 'timedetla', just 'time'. It's just the way it comes when pandas gets the data from my database.
I want a new column 'NewDateTime', with the date from the datetime, and time from the deltatime.
So I have this:
Time DateTime
1 09:01:00 2018-01-01 10:10:10
2 21:43:00 2018-01-01 11:11:11
3 03:20:00 2018-01-01 12:12:12
And I want this:
Time DateTime NewDateTime
1 09:01:00 2018-01-01 10:10:10 2018-01-01 09:01:00
2 21:43:00 2018-01-01 11:11:11 2018-01-01 21:43:00
3 03:20:00 2018-01-01 12:12:12 2018-01-01 03:20:00
At first I tried to set the DateTime column's hours, minutes and seconds to 0. Then I planned to add the timedelta to the datetime.
But when I tried to do:
df['NewDateTime'] = df['DateTime'].dt.replace(hour=0, minute=0, second=0)
I get AttributeError: 'DatetimeProperties' object has no attribute 'replace'
Upvotes: 3
Views: 3770
Reputation: 862441
Use Series.dt.floor
for remove times:
df['NewDateTime'] = df['DateTime'].dt.floor('D') + pd.to_timedelta(df['Time'])
#if necesary convert times to strings
#df['NewDateTime'] = df['DateTime'].dt.floor('D') + pd.to_timedelta(df['Time'].astype(str))
print (df)
Time DateTime NewDateTime
1 09:01:00 2018-01-01 10:10:10 2018-01-01 09:01:00
2 21:43:00 2018-01-01 11:11:11 2018-01-01 21:43:00
3 03:20:00 2018-01-01 12:12:12 2018-01-01 03:20:00
Upvotes: 4