Typeerror: Is Not Convertible to Datetime

Typeerror: Is Not Convertible to Datetime

The problem is somewhat simple. My objective is to compute the days difference between two dates, say A and B.

These are my attempts:

df['daydiff'] = df['A']-df['B']

df['daydiff'] = ((df['A']) - (df['B'])).dt.days

df['daydiff'] = (pd.to_datetime(df['A'])-pd.to_datetime(df['B'])).dt.days

These works for me before but for some reason, I'm keep getting this error this time:

TypeError: class 'datetime.time' is not convertible to datetime

When I export the df to excel, then the date works just fine. Any thoughts?

7

2 Answers

Use pd.Timestamp to handle the awkward differences in your formatted times.

df['A'] = df['A'].apply(pd.Timestamp)  # will handle parsing
df['B'] = df['B'].apply(pd.Timestamp)  # will handle parsing
df['day_diff'] = (df['A'] - df['B']).dt.days

Of course, if you don't want to change the format of the df['A'] and df['B'] within the DataFrame that you are outputting, you can do this in a one-liner.

df['day_diff'] = (df['A'].apply(pd.Timestamp) - df['B'].apply(pd.Timestamp)).dt.days

This will give you the days between as an integer.

4

When I applied the solution offered by emmet02, I got TypeError: Cannot convert input [00:00:00] of type as well. It's basically saying that the dataframe contains missing timestamp values which are represented as [00:00:00], and this value is rejected by pandas.Timestamp function.

To address this, simply apply a suitable missing-value strategy to clean your data set, before using

df.apply(pd.Timestamp)
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.