Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: <class 'datetime.time'> 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?

like image 963
TylerNG Avatar asked Mar 20 '18 16:03

TylerNG


1 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.

like image 134
emmet02 Avatar answered Oct 10 '22 23:10

emmet02