python - 如何使用 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'。
解决方案
您需要设置语言环境
import locale
from datetime import datetime
locale.setlocale(locale.LC_ALL, 'en_US')
dateTimeObj = datetime.strptime('12/01/2020', '%x')
默认情况下(locale=None),年份只有两位数,如提供的链接所示
推荐阅读
- macos - Big Sur 中的元键
- swift - 如何从电话号码中删除破折号、括号和空格?
- javascript - 如果密集使用 setImmediate 会不会有任何不良影响?
- python - Facebook Marketing API Ads Insights 到 Python 中的 CSV
- python - Matplotlib:在 hexbin 图中使用最常见值的 bin 组周围添加边框
- google-photos - 用于存档照片的 Google Photos API
- javascript - 403 在 Vue.js + CodeIgniter 4 中被禁止
- tensorflow - 使用 tensorflow 2.5.0 和 nvidia 11.1 / 455 的 GPU 无法与 Debian 10 一起使用
- python - Pandas:删除符合条件的值
- angular - 角垫表示意图问题