如何使用日期时间库和 strptime 方法将“12/01/2020”转换为日期时间对象?

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

我正在关注这个 directive,它展示了如何使用 datetime 库和 strptime 方法格式化字符串以在 IDLE Python 中转换为 datetime 对象。

这是我输入的内容:

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

这是我收到的错误消息:

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

为什么我会收到错误消息?

我使用此格式字符串使其工作:“%m/%d/%Y”,但我想使用“%x”。

您需要设置语言环境

import locale
from datetime import datetime

locale.setlocale(locale.LC_ALL, 'en_US')

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

默认情况下(locale=None),年份只有两位数,如link提供