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

问题描述

我正在关注此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),年份仅两位数字,如提供的链接所示