Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a datetime.time() object to datetime.datetime object pandas

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 .

like image 963
Sujith Shivaprakash Avatar asked Jan 01 '23 16:01

Sujith Shivaprakash


1 Answers

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
like image 97
ResidentSleeper Avatar answered Feb 11 '23 14:02

ResidentSleeper