Combine Date and Time columns using python pandas
It's worth mentioning that you may have been able to read this in directly e.g. if you were using read_csv
using parse_dates=[['Date', 'Time']]
.
Assuming these are just strings you could simply add them together (with a space), allowing you to apply to_datetime
:
In [11]: df['Date'] + ' ' + df['Time']Out[11]:0 01-06-2013 23:00:001 02-06-2013 01:00:002 02-06-2013 21:00:003 02-06-2013 22:00:004 02-06-2013 23:00:005 03-06-2013 01:00:006 03-06-2013 21:00:007 03-06-2013 22:00:008 03-06-2013 23:00:009 04-06-2013 01:00:00dtype: objectIn [12]: pd.to_datetime(df['Date'] + ' ' + df['Time'])Out[12]:0 2013-01-06 23:00:001 2013-02-06 01:00:002 2013-02-06 21:00:003 2013-02-06 22:00:004 2013-02-06 23:00:005 2013-03-06 01:00:006 2013-03-06 21:00:007 2013-03-06 22:00:008 2013-03-06 23:00:009 2013-04-06 01:00:00dtype: datetime64[ns]
Note: surprisingly (for me), this works fine with NaNs being converted to NaT, but it is worth worrying that the conversion (perhaps using the raise
argument).
The accepted answer works for columns that are of datatype string
. For completeness: I come across this question when searching how to do this when the columns are of datatypes: date and time.
df.apply(lambda r : pd.datetime.combine(r['date_column_name'],r['time_column_name']),1)
You can cast the columns if the types are different (datetime and timestamp or str) and use to_datetime :
df.loc[:,'Date'] = pd.to_datetime(df.Date.astype(str)+' '+df.Time.astype(str))
Result :
0 2013-01-06 23:00:001 2013-02-06 01:00:002 2013-02-06 21:00:003 2013-02-06 22:00:004 2013-02-06 23:00:005 2013-03-06 01:00:006 2013-03-06 21:00:007 2013-03-06 22:00:008 2013-03-06 23:00:009 2013-04-06 01:00:00
Best,