I am trying to write a simple module to store date data from user entered information:
import datetime
formato_dia = ("%Y%m%d","%Y/%m/%d", "%Y-%m-%d")
def dia_manual():
while True:
entrada_dia = input("""Escriba la fecha para la que desea pedir cita previa
(AAAAMMDD, AAAA/MM/DD ó AAAA-MM-DD):
""")
try:
for i in formato_dia:
try:
return(datetime.datetime.strptime(entrada_dia, i))
break
except:
continue
break
except:
print("No se ha introducido una fecha con un formato válido. Por favor, inténtelo de nuevo.")
continue
print("Ha solicitado una cita previa para el día: "+str(dia_manual()))
I would need to know:
- If I enter a date correctly, the result of
dia_manual()
is also correct, that is, an object is generateddatetime.date
that contains the information entered. But: Entering any other value or an incorrect date does not raise an exception, which should be followed by a new request for the information to the user. Instead of that exception,datetime.strptime
it returns aNoneType
. Why?. - On the last line you would need to use
strftime
. How can I find out what format you usedstrptime
to pass it as an argument?
Thank you very much in advance.
If the error is being thrown, that is verifiable if we add a print in except:
If we place an error value using the above we get the following:
So we see that if the string does not match any of the formats, the loop will be traversed and the exceptions will be thrown, but since there is no explicit return, nothing will be returned, that is, None.
If you want to get the format python allows you to return multiple values:
Note: if you realize the outer try-except doesn't make sense, no match in the for-loop will not throw any error.
Update:
If you want to print the string with the original format just return it: