3
I am trying to do a date validation with Python. My exercise asks for the validation of months with 31 days and leap year.
def data_valida(data):
#Valida data. Recebe uma string no formato dd/mm/aaaa e informa
#um valor lógico indicando se a data é válida ou não.
dia, mes, ano = data.split("/")
meses_31 = ('01', '02', '03', '05', '07', '08', '10', '12')
if ano > '0001' and '12' <= mes >= '01' and '31' <= dia >= '01':
if int(ano) % 4 == 0 and mes == '2':
if dia <= '29':
return True
else:
return False
elif mes == '2':
if dia < '29':
return True
else:
return False
if mes == meses_31 and dia <= '31':
return True
elif dia <= '31':
return False
else:
return False
Testing:
def main():
print('Valida datas:')
test(data_valida("01/01/2014"), True)
test(data_valida("31/01/2014"), True)
test(data_valida("00/00/0000"), False)
test(data_valida("30/04/2014"), True)
test(data_valida("31/04/2014"), False)
test(data_valida("30/09/2014"), True)
test(data_valida("31/09/2014"), False)
test(data_valida("30/06/2014"), True)
test(data_valida("31/06/2014"), False)
test(data_valida("30/11/2014"), True)
test(data_valida("31/11/2014"), False)
test(data_valida("32/01/2014"), False)
test(data_valida("01/01/0000"), False)
test(data_valida("01/13/2014"), False)
test(data_valida("01/00/2014"), False)
test(data_valida("29/02/2014"), False)
test(data_valida("29/02/2016"), True)
I’ve tried to find content on and even the closest I’ve come is the current algorithm. Whenever I arrive in the leap year I can’t fix and this time the code seems ok, it’s returning False
for everything.
if mes == meses_31
doesn’t make much sense, I think the right thing here isif mes in meses_31
. This is because we want to know if themes
is one of the elements ofmeses_31
, and not if it is equal to the entire tuple (all elements). The condition below this (elif dia <= '31': return False
) also has a problem in logic, a day less than or equal to 31 may be valid yes. An example is the day30/04/2014
. You want to try to work it out from this?– AlexCiuffa
And pass the dates (day, month and year) to integers. Comparing string with string is different from comparing integers with integers.
'04' >= '02'
returnsTrue
, but'04' >= '2'
returnsFalse
. When comparing strings, Python takes the ASCII value of the characters to compare.– AlexCiuffa
Thanks for the tips. I think I’ve managed to finish now rs. I haven’t done the conversion to integers you indicated. Anyway, could you tell me what would be the most 'right' way to do the conversion? I’ll post how it went down
– joao medaca