whats_wrong
whats_wrong

Reputation: 11

Handle the calculation of two dates in two different months

I am facing this simple issue in the following code:

df['Diff'] = df['updated'] - df['created'] 

the date diff returns a negative number of days when condition meets (for example) the case below:

df['updated'] == "2020-04-01" and "df['created'] == "2020-03-21" 

Is there a way (that I can probably miss as I am new at python) other than build a def to apply on a specific columns to return the correct number of days and not "-20" which is the basic result between updated and created?

Many thanks

Upvotes: 0

Views: 35

Answers (1)

NYC Coder
NYC Coder

Reputation: 7604

Do this for difference:

df['updated'] = pd.to_datetime(df['updated'], format='%Y-%m-%d')
df['created'] = pd.to_datetime(df['created'], format='%Y-%m-%d')
df['diff'] = df['updated'] - df['created']
print(df)

     updated    created    diff
0 2020-04-01 2020-03-21 11 days

Upvotes: 1

Related Questions