Difference between two dates in Python


I have two different dates and I want to know the difference in days between them. The format of the date is YYYY-MM-DD.

I have a function that can ADD or SUBTRACT a given number to a date:

def addonDays(a, x):
   ret = time.strftime("%Y-%m-%d",time.localtime(time.mktime(time.strptime(a,"%Y-%m-%d"))+x*3600*24+3600))      
   return ret

where A is the date and x the number of days I want to add. And the result is another date.

I need a function where I can give two dates and the result would be an int with date difference in days.

Asked By: mauguerra



Use - to get the difference between two datetime objects and take the days member.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)
Answered By: Fred Foo

I tried the code posted by larsmans above but, there are a couple of problems:

1) The code as is will throw the error as mentioned by mauguerra
2) If you change the code to the following:

    d1 = d1.strftime("%Y-%m-%d")
    d2 = d2.strftime("%Y-%m-%d")
    return abs((d2 - d1).days)

This will convert your datetime objects to strings but, two things

1) Trying to do d2 – d1 will fail as you cannot use the minus operator on strings and
2) If you read the first line of the above answer it stated, you want to use the – operator on two datetime objects but, you just converted them to strings

What I found is that you literally only need the following:

import datetime

end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)

print difference_in_days
Answered By: schalkneethling

Another short solution:

from datetime import date

def diff_dates(date1, date2):
    return abs(date2-date1).days

def main():
    d1 = date(2013,1,1)
    d2 = date(2013,9,13)
    result1 = diff_dates(d2, d1)
    print '{} days between {} and {}'.format(result1, d1, d2)
    print ("Happy programmer's day!")

Answered By: 0x8BADF00D

Try this:

data=pd.read_csv('C:UsersDesktopData Exploration.csv')
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']

m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()

m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
Answered By: user8359392

pd.date_range(‘2019-01-01’, ‘2019-02-01’).shape[0]

Answered By: ar91

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])
Answered By: Marcus Trugilho

You can use the third-party library dateutil, which is an extension for the built-in datetime.

Parsing dates with the parser module is very straightforward:

from dateutil import parser

date1 = parser.parse('2019-08-01')
date2 = parser.parse('2019-08-20')

diff = date2 - date1


Answer based on the one from this deleted duplicate

Answered By: Tomerikoo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.