首页 > 解决方案 > 如何使用 datetime 库和 strptime 方法将 '12/01/2020' 转换为 datetime 对象?

问题描述

我正在遵循这个指令,该指令显示了如何在 IDLE 中使用 datetime 库和 strptime 方法格式化字符串以转换为 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'。

标签: pythonpython-3.xdatetimestrptime

解决方案


您需要设置语言环境

import locale
from datetime import datetime

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

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

默认情况下(locale=None),年份只有两位数,如提供的链接所示


推荐阅读