There is dataframe as:
time date
11:42:14.556 2023-12-10 10:12:00.129465868
11:42:16.005 2023-12-11 15:25:00.759067848
11:42:32.175 2023-12-12 13:56:00.653087940
Columns are object types.
How to take date from “date” column and add it to “time” column?
Use dt.normalize
after converting to_datetime
:
df['time'] = pd.to_datetime(df['date']).dt.normalize().add(pd.to_timedelta(df['time']))
Or if both columns are strings, extract
the date and concatenate:
df['time'] = df['date'].str.extract('(\S+)', expand=False)+' '+df['time']
# or
df['time'] = df['date'].str[:10]+' '+df['time']
Output:
time date
0 2023-12-10 11:42:14.556 2023-12-10 10:12:00.129465868
1 2023-12-11 11:42:16.005 2023-12-11 15:25:00.759067848
2 2023-12-12 11:42:32.175 2023-12-12 13:56:00.653087940
Use Series.str.split
with add times and convert output to datetimes:
df['time'] = pd.to_datetime(df['date'].str.split().str[0] + ' ' + df['time'].astype(str))
Or Series.dt.normalize
with to_timedelta
:
df['time'] = df['date'].dt.normalize() + pd.to_timedelta(df['time'])
print (df)
time date
0 2023-12-10 11:42:14.556 2023-12-10 10:12:00.129465868
1 2023-12-11 11:42:16.005 2023-12-11 15:25:00.759067848
2 2023-12-12 11:42:32.175 2023-12-12 13:56:00.653087940
Can you clarify what are the dtype of the original columns?
The type of data determines the method.
All columns are object types
Thanks @harp1814 for clarifying, then both my approaches should work 🙂
@PandaKim the nice thing with
to_datetime
is that it can take a datetime column as input, so in doubt the conversion doesn’t hurt.