python - 为什么即使格式匹配,Python 日期时间也会失败 {Date}2016-11-22T11 :49:21. 826-05:00

标签 python python-3.x datetime

我正在尝试在 python 3.6 中格式化日期时间,如下所示,

datetime.datetime.strptime(date_string, "{Date}%Y-%m-%dT%H:%M:%S.%f%z")

但是,输入字符串 {Date}2016-11-22T11:49:21.826-05:00 的格式化失败,并出现以下错误。

Traceback (most recent call last):   File "./test-date.py", line 168, in get_date
  date_time_ = datetime.datetime.strptime(date_string, "{Date}%Y-%m-%dT%H:%M:%S.%f%z").replace(tzinfo=None)   
File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
  tt, fraction = _strptime(data_string, format)   
File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
  (data_string, format))
ValueError: time data '{Date}2016-11-22T11:49:21.826-05:00' does not match format '{Date}%Y-%m-%dT%H:%M:%S.%f%z'

最佳答案

因为输入%z的正确方法是-0500而不是-05:00

>>> datetime.datetime.strptime('2016-11-22T11:49:21.826-0500', "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2016, 11, 22, 11, 49, 21, 826000, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))

关于python - 为什么即使格式匹配,Python 日期时间也会失败 {Date}2016-11-22T11 :49:21. 826-05:00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918325/

相关文章:

python - 如何将日期转换为日期时间?

c# - 查找c#中某个子字符串后面出现的第一个数字的索引

MySQL - 如何从 rss 提要转换日期时间

python - ObjectListView 使用逗号对整数进行排序和格式化?

python - django 中最终用户的动态表单

python - 当存在重复项时查找列表之间的差异

python - 如何将python程序完全转化为exe文件?

python - 给定外部订单,按日期时间月份的 Pandas 订单行

python - xonsh 中遍历文件行的最佳方法是什么?

Python 3.7.3 无意中安装在 Mac OS 10.15.1 上 - 现在包含在 Xcode Developer Tools 11.2 中?