How to subtract two dates using Python?

Asked

Viewed 15,165 times

8

How do I know the difference in days between two dates using Python?

For example; How to know how many days there are between 22/11/2013 and 25/03/2014, considering a possible leap year.

3 answers

9


Just instantiate the two dates as objects datetime.date and subtract them:

In [1]: import datetime

In [2]: data1 = datetime.date(day=22, month=11, year=2013)

In [3]: data2 = datetime.date(day=25, month=3, year=2014)

In [4]: data2-data1
Out[4]: datetime.timedelta(123)

In [5]: diferenca = data2-data1

In [6]: diferenca.days
Out[6]: 123

7

There’s another way too:

# -*- coding: utf-8 -*-

from datetime import datetime

def diff_days(date1, date2):
    d1 = datetime.strptime(date1, "%d-%m-%Y")
    d2 = datetime.strptime(date2, "%d-%m-%Y")
    return abs((date2 - date1).days)
  • 1

    I think that’s the same way.

  • It is exactly the same way, the difference is that the accepted answer initializes the dates with datetime.date, while this one does it with datetime.strptime.

-4

You can also use variables instead of fixed values.

For example:

import datetime    
tempo = datetime.date.today()    
dia = int(input('Dia de Nascimento: '))    
mes = int(input('Mês de Nascimento: '))    
ano = int(input('Ano de nascimento: '))    
tempo2 = datetime.date(day=dia, month=mes, year=ano)    
alistamento = tempo - tempo2    
print(alistamento)

He will return you the amount of days. In fact I want him to return me in Years, not in days.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.