'date is not coming in same format python csv

I am trying to convert string to date and then adding in csv file , but what I am getting is date is in diff format in few columns and diff for others for example :

as shown in image

def update_date_format(date_time):
    try:
        date_formating = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S.%f')
    except:
        date_formating = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S')

    final_date = date_formating.strftime('%m/%d/%Y %I:%M %p')
    return final_date

and I am using try : except because date is coming some times without milliseconds:

with milliseconds getting like this 2022-02-17 08:29:36.345374 without milliseconds getting like this 2022-02-17 08:29:36

EDIT this issue is facing when opening csv with Excel .



Sources

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

Source: Stack Overflow

Solution Source