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.
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.
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)
-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.
Kelvin Rafael, Stack Overflow is not a forum or social network We are a website of questions and technical answers about programming. It would be good for you to do our [tour] to know the basics of the site and read the topic [Answer] to get a sense of what and how to respond. See also some guidelines that will help you: Stack Overflow Survival Guide in English
Browser other questions tagged python datetime
You are not signed in. Login or sign up in order to post.
I think that’s the same way.
– Eduardo
It is exactly the same way, the difference is that the accepted answer initializes the dates with
datetime.date
, while this one does it withdatetime.strptime
.– Rodrigo Deodoro