Search code examples
pythonpython-3.xdatetimestrptime

How do I convert '12/01/2020' to a datetime object using the datetime library and the strptime method?


I'm following this directive that shows how to format the string to convert to a datetime object in Python in IDLE using the datetime library and the strptime method.

Here is what I type in:

dateTimeObj = datetime.strptime('12/01/2020', '%x')

Here is the error message I get:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    dateTimeObj = datetime.strptime('12/01/2020', '%x')
  File "C:\Program Files\Python38\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Program Files\Python38\lib\_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: 20

Why am I getting an error?

I got it to work using this format string: '%m/%d/%Y', but I want to use '%x'.


Solution

  • You'll need to set the locale

    import locale
    from datetime import datetime
    
    locale.setlocale(locale.LC_ALL, 'en_US')
    
    dateTimeObj = datetime.strptime('12/01/2020', '%x')
    

    By default (locale=None), the year is only two digits, as shown in the link provided