datetime.strptime returns 'NoneType' objects

4

I am trying to write a simple module to store date data from the information entered by the user:

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 generated datetime.date containing the information entered. But enter any other value or an incorrect date, it is not generated an exception, which should be followed by a new request from the information to the user. Instead of that exception, datetime.strptime returns a NoneType object. Why?.
  • On the last line I would need to use strftime . How can I know what format did strptime use to pass it as an argument?
  • Thank you very much in advance.

        
    asked by Ruben García Tutor 06.08.2018 в 14:45
    source

    1 answer

    2

    If the error is being thrown, that is verifiable if we add a print in except:

    try:
        return(datetime.datetime.strptime(entrada_dia, i))
        break
    except:
        print("error")
        continue
    

    If we put an error value using the above we get the following:

    error
    error
    error
    Ha solicitado una cita previa para el día: None
    

    So we see that if the string does not match some 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 obtain the python format, you can return multiple values:

    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): """)
            for formato in formato_dia:
                try:
                    return datetime.datetime.strptime(entrada_dia, formato) , formato
                except ValueError:
                    pass
            print("No se ha introducido una fecha con un formato válido. Por favor, inténtelo de nuevo.")
    
    resultado = dia_manual()
    if resultado is not None:
        dtime, formato = resultado
        print("Ha solicitado una cita previa para el día: {}".format(dtime))
        print("El formato elegido es {}".format(formato))
    

    Note: if you notice the external try-except it does not make sense, that there is 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:

    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): """)
            for formato in formato_dia:
                try:
                    datetime.datetime.strptime(entrada_dia, formato)
                    return entrada_dia
                except ValueError:
                    pass
            print("No se ha introducido una fecha con un formato válido. Por favor, inténtelo de nuevo.")
    
    print("Ha solicitado una cita previa para el día: {}".format(dia_manual()))
    
        
    answered by 06.08.2018 / 15:01
    source