How can I combine datetime.date and datetime.time columns in pandas dataframe?

Viewed 2207

Given df

          Date      Time    Data     
3   2017-08-10  15:15:00    a    
0   2017-08-11  15:15:00    b    
1   2017-08-12  15:15:00    c    
2   2017-08-13  15:15:00    d    
1   2017-08-14  15:15:00    e    

And

print (type(df['Date'].iat[0]))
<class 'datetime.date'>

print (type(df['Time'].iat[0]))
<class 'datetime.time'>

How can I combine df.Date and df.Time into a DateTime column that is a datetime object ??:

        Date        Time    Data  DateTime   
3   2017-08-10  15:15:00    a     2017-08-10 15:15:00
0   2017-08-11  15:15:00    b     2017-08-11 15:15:00
1   2017-08-12  15:15:00    c     2017-08-12 15:15:00
2   2017-08-13  15:15:00    d     2017-08-13 15:15:00
1   2017-08-14  15:15:00    e     2017-08-14 15:15:00

What I tried:

df['DateTime'] = df.apply(lambda r : pd.datetime.combine(r['Date'],r['Time']),1)

This works well as intended, However, I would prefer a vectorized operation and I get the following msg:

C:\Users\User\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: 
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-
docs/stable/indexing.html#indexing-view-versus-copy
if __name__ == '__main__':
2 Answers

I'm late to the party... Vaishali's answer works if "Date" is a datetime-like object.

str(date) will give yyyy-mm-dd output according to docs, so you can do:

pd.to_datetime(df['Date'].astype(str) + df['Time'].astype(str), format = '%Y-%m-%d%H:%M:%S')

However, I have not tested this for speed.

Related