Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove "days" when computing the difference between two dates?

When computing the difference between two dates using the following:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date'])

I get a third column with "x Days".

How can I convert "x Days" into int "x". e.g., "50 days" into "50"?

Someone in a previous thread suggested to use:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days

but using that I get an error of type:

"'Series' object has no attribute 'dt"

How I can fix the issue please?

like image 775
SBad Avatar asked Jul 29 '26 04:07

SBad


1 Answers

If it is a string variable. then you can do the following and strip of the unwanted part. (say your variable is xDays)

df["xDays"] = df["xDays"].map(lambda x: x[:-5])

if it is a timedelta value you can do following

df["xDays"].dt.days
like image 153
Rao Sahab Avatar answered Jul 31 '26 18:07

Rao Sahab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!