import pandas as pd
import datetime
df = pd.DataFrame([{'st':datetime.datetime.strptime('21:00:00','%H:%M:%S').time(),'et':datetime.datetime.strptime('22:00:00','%H:%M:%S').time()}, {'st':datetime.datetime.strptime('1:00:00','%H:%M:%S').time(),'et':datetime.datetime.strptime('3:00:00','%H:%M:%S').time()}])
Out[183]: df
et st
0 22:00:00 21:00:00
1 03:00:00 01:00:00
I would like to be able to convert the above dataframe with new fields having datetime.datetime
objects with two other extra columns such as here having any dummy date in it and using the time from their respective rows:
et st sdate_time edate_time
0 22:00:00 21:00:00 2018-01-01 21:00:00 2018-01-01 22:00:00
1 03:00:00 01:00:00 2018-01-01 1:00:00 2018-01-01 3:00:00
The approach I have tried is using apply method
df['et'].apply(lambda et: pd.datetime.combine(datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date(),et))
but turns out that the dataframe could be really huge and I would like to vectorize the above operation without the apply method .
Try this
date = str(datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date())
df['edate_time'] = pd.to_datetime(date + " " + df.et.astype(str))
et st edate_time
0 22:00:00 21:00:00 2018-01-01 22:00:00
1 03:00:00 01:00:00 2018-01-01 03:00:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With