user3042850
user3042850

Reputation: 317

Concatenating Columns into Dates

Okay I currently have a column of dates whose dtype is object.

Output is as follows:

720344    31/12/2016
720345    31/12/2016
720346    31/12/2016
720347    31/12/2016
720348    31/12/2016

Then I have a column of time whose dtype is timedelta64[ns] and it's output looks like

10       00:15:04
11       00:12:20
12       00:14:37
13       00:18:42

I've read a couple of threads and it seems I need to use the pd.to_datetime function somehow.

I've tried:

pd.to_datetime(dfdate['INCIDENT_DATE'] + " " + dfdate['DispatchTime'])

But I get the error:

TypeError: ufunc add cannot use operands with types dtype('<U11') and dtype('<m8[ns]')

I guess it doesn't like the object + timedelta command.

Then I tried to convert the time to a str with this:

pd.to_datetime(dfdate['INCIDENT_DATE'] + " " + str(dfdate['DispatchTime']))

But now i get a different error:

ValueError: Unknown string format

Upvotes: 1

Views: 33

Answers (1)

jezrael
jezrael

Reputation: 863671

I think is necessary convert column INCIDENT_DATE to datetimes by to_datetime and then add DispatchTime column, because timedeltas:

print (dfdate.dtypes)
INCIDENT_DATE             object
DispatchTime     timedelta64[ns]
dtype: object

dfdate['date'] = pd.to_datetime(dfdate['INCIDENT_DATE']) + dfdate['DispatchTime']
print (dfdate)
       INCIDENT_DATE DispatchTime                date
720344    31/12/2016     00:15:04 2016-12-31 00:15:04
720345    31/12/2016     00:12:20 2016-12-31 00:12:20
720346    31/12/2016     00:14:37 2016-12-31 00:14:37
720347    31/12/2016     00:18:42 2016-12-31 00:18:42

Upvotes: 2

Related Questions