I have a pandas dataframe like this..
created_time reached_time
2016-01-02 12:57:44 14:20:22
2016-01-02 12:57:44 13:01:38
2016-01-03 10:38:51 12:24:07
2016-01-03 10:38:51 12:32:11
2016-01-03 10:38:52 12:23:20
2016-01-03 10:38:52 12:51:34
2016-01-03 10:38:52 12:53:33
2016-01-03 10:38:52 13:04:08
2016-01-03 10:38:52 13:13:40
I want to subtract these two date columns and want to get time
I am doing following in python
speed['created_time'].dt.time - speed['reached_time']
But it gives me following error
TypeError: ufunc subtract cannot use operands with types dtype('O') and dtype('<m8[ns]')
datatype of created_time
is object
and datatype of reached_type
is timedelta64[ns]
You could drop down to NumPy arrays and do the datetime/timedelta arithmetic there. First, create an array of dates of dtype
datetime64[D]
:Then you have two options: you could convert
reached_time
to dates, and subtract dates from dates:or you could convert
created_time
to timedeltas, and subtract timedeltas from timedeltas:yields
Using HRYR's improvement, you can do the computation without dropping down to NumPy arrays (i.e. no need to access
.values
):Convert
created_time
column to datetime first:Then use
df["created_time"] - df["created_time"].dt.normalize()
to get the time part astimedelta
type.