pythondatetimedatetime-formatdatetime-parsing

ValueError in time-date data


I'm facing issue in matching the format of time date data time data '03-MAY-22 02.42.33.000000000 AM' does not match format '%d-%b-%y %I.%M.%S.%f %p' what should be the correct format for this date-time data?

For this time-date data '03-MAY-22 02.42.33.000000000 AM' I've written this format '%d-%b-%y %I.%M.%S.%f %p' but this is not matching


Solution

  • The standard library doesn't support a resolution for the fraction-of-second finer than microseconds. You can remove the last three digits from the fraction-of-second and then parse the obtained string in the usual way.

    from datetime import datetime
    import re
    
    str_dt = '03-MAY-22 02.42.33.000000000 AM'
    str_dt = re.sub(r'(\.\d{6})(\d{3})', r'\1', str_dt)
    print(str_dt)
    
    dt = datetime.strptime('03-MAY-22 02.42.33.000000 AM', '%d-%b-%y %H.%M.%S.%f %p')
    print(dt)
    

    Output:

    03-MAY-22 02.42.33.000000 AM
    2022-05-03 02:42:33
    

    Check this regex demo to understand the regex pattern used in the solution. This solution replaces the regex match with group 1 of the match.