0

Dataframe has 2 dates which are of "object" datatype. StartDate and EndDate are in the mm/dd/yyyy format.

  Name        StartDate          EndDate
  bou1        1/9/2017           1/10/2017
  bou2        12/31/2016         1/10/2017          

Output:

  Name        StartDate          EndDate         Diff
  bou1        1/9/2017           1/10/2017       1
  bou2        12/31/2016         1/10/2017       10

Any suggestions would be appreciated !!

2
  • pd.to_datetime(df.EndDate)-pd.to_datetime(df.StartDate) Commented Jun 29, 2018 at 21:57
  • @Wen: Thank you, but I get the invalid syntax error Commented Jun 29, 2018 at 22:00

2 Answers 2

1

you first need to convert to datetime for those columns and then subtract.

try

df['startDate'] = pd.to_datetime(df['startDate'])
df['EndDate'] = pd.to_datetime(df['EndDate'])
df['difInDate'] = (abs(df['startDate'].sub(df['EndDate'], axis = 0))) / np.timedelta64(1, 'D')
print(df['difInDate'])

abs is just to make it days positive because, you are subtracting from small date to big date alternatively you can use (df['EndDate'].sub(df['StartDate'] too

Sign up to request clarification or add additional context in comments.

Comments

0
# Recreating your dataframe with dates stored as strings
df = pd.DataFrame({'Name'     : ['bou1', 'bou2'],               
                   'StartDate': ['01/09/2017','12/31/2016'],    
                   'EndDate'  : ['01/10/2017', '01/10/2017']}) 

# Date strings converted with pd.Datetime
df['StartDate'] = pd.to_datetime(df['StartDate'])               
df['EndDate'] = pd.to_datetime(df['EndDate'])

# .dt handles your calculation and .days outputs in days
df['Diff'] = (df['EndDate'] - df['StartDate']).dt.days          

# Just prints the columns in your order
df[['Name', 'StartDate', 'EndDate', 'Diff']]                    

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.