'Logging message inside except exception

I am trying to use logging when try fails. I have a for loop for converting a string of date into datetime format.

For example, converting "03/05/2021" to 2021-05-03. However, there are typoed dates such as 03/052021. If the loop encounters such typoed date, I want it to create a log.

for id in range(1,items):
    try:
        dt_bd_lists.append(datetime.strptime(bd_lists[i+1], '%d/%m/%Y'))
        #print(dt_bd_lists[id])
    except:
        dt_bd_lists.append(bd_lists[id+1])
        #LOG_FILENAME = 'error_log'
        #logging.basicConfig(
        #filename=LOG_FILENAME,
        #level=logging.ERROR
        #)
        #logging.error('Error processing line %(lineno)d for ID %d', id)

For logging message, I want to create, "Error processing (line number) for (ID)."

Unfortunately, I am getting logging error and am stuck. What would solve this issue?



Solution 1:[1]

This will not help you with the logging, I would need the error produced by the logging for that, but maybe you can "clean" your data.

By replacing all slashes / with empty strings "" you can ignore those typos. Then you need to adjust the format of the date to "%d%m%Y" and you are good to go (just remove the slashes).

from datetime import datetime

date_strings = ["03/05/2021", "03/052021"]

for date_string in date_strings:
    date_string = date_string.replace("/", "")  # replace / with empty string

    date_time_obj = datetime.strptime(date_string, '%d%m%Y')
    print(date_time_obj)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Loxbie