shivashish bidua
shivashish bidua

Reputation: 53

How can I resolve this " TypeError: cannot concatenate 'str' and 'datetime.time' objects"

enter image description here

The image above shows my data set. I want to add 'DATE'(string) and 'SCHEDULED_DEPARTURE'(datetime) and form data in a single column. While I am doing this using:

DST = pd.to_datetime(flights_drop_null['DATE'] + ' ' + flights_drop_null['SCHEDULED_DEPARTURE_FINAL'])
flights_drop_null.insert(loc=5,column='DATE_SCHEDULED_DEPARTURE',value=DST)

I get that error.

Upvotes: 2

Views: 29298

Answers (1)

mikebob
mikebob

Reputation: 321

Well, you are trying to combine disparate types. You cannot joint a string with a datetime.time object simply because there isn't just one way to format your time object, you could print it as HH, or HH:MM or HH:MM:SS, etc.

If all you need in the end is to have that data in a single column to display, then I would recommend you convert the datatime.time object to a string. If, however, you want to perform logic on the combined date and time, then I would suggest you convert the date string into a datetime.date object and then combine those two together into a datetime.datetime object.

By the way, I do not know what your pd.to_datetime() function does, so I'm just going to ignore it for now.

Converting to a string

departure_time = flights_drop_null['SCHEDULED_DEPARTURE_FINAL']
DST = flights_drop_null['DATE'] + ' ' + departure_time.strftime("%H:%M:%S")
flights_drop_null.insert(loc=5,column='DATE_SCHEDULED_DEPARTURE',value=DST)

Converting to a datetime

Well, I'm sure there are more clever ways, but the quickest I can prototype is to first convert to a string, then convert back to a datetime object.

import datetime
departure_time = flights_drop_null['SCHEDULED_DEPARTURE_FINAL']
DST = flights_drop_null['DATE'] + ' ' + departure_time.strftime("%H:%M:%S")
departure_datetime = datetime.datetime.strptime(DST, "%m/%d/%Y %H:%M:%S")

Upvotes: 5

Related Questions